Javascript - if with asynchronous case

2020-01-26 12:02发布

问题:

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