TrevTheDev
TrevTheDev

Reputation: 2737

How to wait for a promise to be fulfilled before continuing

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;

Upvotes: 12

Views: 14882

Answers (3)

MonsieurDart
MonsieurDart

Reputation: 6035

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.

Upvotes: 2

TrevTheDev
TrevTheDev

Reputation: 2737

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.

Upvotes: 7

jacquard
jacquard

Reputation: 1307

You can start to show a loading gif, then you can subscribe to the didLoad event for the record, inside which you can continue your actual processing..

    record = App.User.find(1);

    //show gif..

    record.on("didLoad", function() {
        console.log("ren loaded!");
    });

    //end gif; continue processing..

Upvotes: 1

Related Questions