Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a promise to be fulfilled before continuing

Tags:

ember.js

How can I wait until a Promise is resolved before executing the next line of code?

e.g.

var option = null;
if(mustHaveOption){
   option = store.find("option", 1).then(function(option){ return option })
}
//wait until promise is resolved before returning this value
return option;
like image 580
TrevTheDev Avatar asked Jan 28 '14 05:01

TrevTheDev


People also ask

How do you wait for a Promise to complete?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.

How do you wait for setTimeout to finish?

How to Wait for a Function to Finish in JavaScript. Using a Callback Function With setTimeout() to Wait for a Function to Finish. Using await Keyword and setTimeout() to Wait for a Function to Finish.

Can a Promise be awaited multiple times?

The implication of this is that promises can be used to memoize async computations. If you consume a promise whose result will be needed again later: consider holding on to the promise instead of its result! It's fine to await a promise twice, if you're happy to yield twice.

What are stages of promises?

fulfilled: Action related to the promise succeeded. rejected: Action related to the promise failed. pending: Promise is still pending i.e. not fulfilled or rejected yet. settled: Promise has fulfilled or rejected.


2 Answers

With ES6, you can now use the async/await syntax. It makes the code much more readable:

async getSomeOption() {
  var option = null;
  if (mustHaveOption) {
    option = await store.find("option", 1)
  }
}
return option;

PS: this code could be simplified, but I'd rather keep it close from the example given above.

like image 74
MonsieurDart Avatar answered Oct 26 '22 17:10

MonsieurDart


rallrall provided the correct answer in his comment: you can't

The solution for me was to redesign my code to return promises and then the receiving function must evaluate the result something along the lines of:

function a(){
  var option = null;
    return  mustHaveOption ? store.find("option", 1) : false;
  }    
}

function b(){
   res = a();
   if (!res){
       res.then(function(option){
          // see option here
       });
   }
} 

Another key solution for me was to use a hash of promises. One creates an array of all the promises that must be resolve before executing the next code:

Em.RSVP.Promise.all(arrayOfPromises).then(function(results){
   //code that must be executed only after all of the promises in arrayOfPromises is resolved
});

It tooks me a while to wrap my head around this async way of programming - but once I did things work quite nicely.

like image 21
TrevTheDev Avatar answered Oct 26 '22 17:10

TrevTheDev