Javascript - if with asynchronous case

孤街浪徒 提交于 2019-11-26 12:33:54

问题


My question is a bit regards concept.

A lot of times there is this such situation:

if(something){
    someAsyncAction();
}else{
    someSyncAction();
}

// Continue with the rest of code..
var a = 5;

The problem with this such case is clear, i don\'t want the var a = 5 to be call unless someAsyncAction() or someSyncAction() will done, now, cause soAsyncAction() is asynchronous the only way (i can think of) to solve this situation is something like that:

var after = function(){
    // Continue with the rest of code..
    var a = 5;
}

if(something){
    someAsyncAction(after);
}else{
    someSyncAction();
    after ();
}

BUT, this code is ugly, hard to read and looks like anti-pattern and problematic.

I trying to think maybe i can find some solution for that with Promises (using Bluebird at the backend) but can\'t find something.

Is anyone faced this before and can help me figure it out?

Thanks!


回答1:


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;
});


来源:https://stackoverflow.com/questions/29802311/javascript-if-with-asynchronous-case

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