使用Javascript - 如果与异步的情况下,

使用Javascript  - 如果与异步的情况下,

问题描述:

我的问题是有点概念方面

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;

此这种情况下的问题是清楚的,我不想让 VAR 1 = 5 要打电话,除非 someAsyncAction() someSyncAction()会做的,现在,事业 soAsyncAction()是异步的唯一途径(我能想到的)来解决这个情况是类似的东西:

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

但是,这code是丑陋的,难以阅读和看起来像反模式和有问题的。

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?

谢谢!

通过诺言,你将有一个类似的模式与回调,只有你会先存储结果,而不必调用/传递回调两次:

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