Javascript - if with asynchronous case

后端 未结 1 1178
离开以前
离开以前 2020-11-29 14:11

My question is a bit regards concept.

A lot of times there is this such situation:

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


        
相关标签:
1条回答
  • 2020-11-29 14:40

    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;
    });
    
    0 讨论(0)
提交回复
热议问题