Javascript - if with asynchronous case

大兔子大兔子 提交于 2019-11-27 02:16:56

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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!