使用Javascript - 如果与异步的情况下, [英] Javascript - if with asynchronous case

查看:147
本文介绍了使用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;
});

这篇关于使用Javascript - 如果与异步的情况下,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆