Javascript - 如果有异步情况 [英] Javascript - if with asynchronous case

查看:29
本文介绍了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 a = 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 ();
}

但是,这段代码很丑,难以阅读,而且看起来像反模式和有问题的.

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

我想也许我可以通过 Promises(在后端使用 Bluebird)找到一些解决方案,但找不到.

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?

谢谢!

推荐答案

使用 promises,您将拥有与使用回调类似的模式,只是您会先存储结果,而不必两次调用/传递回调:

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天全站免登陆