Javascript – if with asynchronous case

With promises, you would have a similar pattern as with the callback, only you would store the result first and not have to call/pass the callback twice:

function after(result) {
    // Continue with the rest of code..
    var a = 5;
}
var promise;
if (something){
    promise = someAsyncAction();
} else {
    promise = Promise.resolve(someSyncAction());
}
promise.then(after);

Or in short, you’d use the conditional operator and structure it much more straightforward:

(something
  ? someAsyncAction()
  : Promise.resolve(someSyncAction())
).then(function(result) {
    // Continue with the rest of code..
    var a = 5;
});

Leave a Comment