How to wait for a promise to be fulfilled before continuing

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..

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.


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.

Tags:

Ember.Js