Question

This might seem like an abuse of promises or an "you're doing it all wrong" question, if so please correct me. I ran into several points where I wanted to synchronize calls that by default were asynchronous in Ember.js. Here is a small example:

class service extends Ember.Object
  someProperty: null

  doSomething: ->
    #this.store was injected during initialisation
    this.store.find("someModel", someSelector).then((result) =>
      @someProperty = result.someField
      console.log "promise fulfilled"
  )

calling the following code:

service.doSomething()
console.log "this should be second"

will result in:

"this should be second"
"promise fulfilled"

which means that if someone calls the method and expects the property someProperty to be set after the call returns it will not be the case. The only way to synchronise that I would see is to call it like "service.doSomething().then(-> ....)". This would imply the caller needs to know that a promise is returned.

Is there any way to wait inside doSomething method until the promise is resolved and ONLY then return?

Was it helpful?

Solution

This would imply the caller needs to know that a promise is returned

The caller obviously always needs to know what the function they are calling returns and even what parameters it takes. So you do not really have a problem here.

OTHER TIPS

As you already guessed, this is not a good idea. Javascript Development is all about thinking and working asynchronously and therefore the clients of your service should be exposed to the API of Promises. And i think that is a fair requirement, as promises are an easy to concept to learn to simplify asynchronous programming a lot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top