JS Promises-仅异步单个路径时的if-else流 [英] JS Promises - if-else flow when only single path is async

查看:64
本文介绍了JS Promises-仅异步单个路径时的if-else流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重写一些旧代码,这些代码是使用sync ajax构建的(太糟糕了).现在,我正在使用Promises(特别是Bluebird).在很多情况下,函数具有很多路径,而其中只有一个是异步的.

I'm rewriting some legacy code, which was build using sync ajax (so so bad). Now I'm using Promises (specifically Bluebird). There are a lot of situations, where function has a lot of paths, from which only one is async.

问题是我必须识别所有路径并手动从每个路径返回新的Promise.像这样:

The problem is that I have to identify all paths and manually return new promise from each of them. Like this:

function syncFn() {
    // sync code return
}
function asyncFn() {
    // some async code here that return Promise
}
function myMegaFunction() {
    if ( ... ) {
        return Promise.resolve(syncFn());
    }
    else if ( ... ) {
        if ( ... ) {
            return Promise.resolve(syncFn());
        }
        else if ( ... ) {
            return Promise.resolve(syncFn());
        }
        else {
            return asyncFn(); // only async function here
        }
    }
    else {
        return Promise.resolve();
    }
}

是否有某种方式或模式可以简化此过程?也许像-如果返回未定义,然后包装为空的诺言?

Is there some way or pattern, that could simplify this? Maybe something like - if return undefined, then wrap as empty promise?

推荐答案

您可以使用 Promise.method 的辅助工具:

You can use the Promise.method helper for this:

var myMegaFunction = Promise.method(function myMegaFunction() {
    // return values
    // throw errors
    // return promises
});

…和myMegaFunction(…)将始终返回承诺.它会自动捕获异常,并将函数的结果包装在Promise.resolve(…)中.

…and myMegaFunction(…) will always return a promise. It automatically catches exceptions, and wraps the result of your function in a Promise.resolve(…).

这篇关于JS Promises-仅异步单个路径时的if-else流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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