如何打破承诺链 [英] how to break promise chain

查看:145
本文介绍了如何打破承诺链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是这样的承诺,

function getMode(){
    var deferred = Promise.defer();

    checkIf('A')
    .then(function(bool){
        if(bool){
            deferred.resolve('A');
        }else{
            return checkIf('B');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('B');
        }else{
            return checkIf('C');
        }
    }).then(function(bool){
        if(bool){
            deferred.resolve('C');
        }else{
            deferred.reject();
        }
    });

    return deferred.promise;
}

checkIf 返回承诺,是的 checkIf 无法修改

如何突破在第一场比赛的链? (除了明确抛出错误之外的任何其他方式?)

How do I break out of the chain at the first match? (any way other than explicitly throwing error?)

推荐答案

我认为你不想在这里找到链条。以同步的方式,你已经写了

I think you don't want a chain here. In a synchronous fashion, you'd have written

function getMode(){
    if (checkIf('A')) {
        return 'A';
    } else {
        if (checkIf('B')) {
            return 'B';
        } else {
            if (checkIf('C')) {
                return 'C';
            } else {
                throw new Error();
            }
        }
    }
}

和这是应该如何转换为承诺:

and this is how it should be translated to promises:

function getMode(){
    checkIf('A').then(function(bool) {
        if (bool)
            return 'A';
        return checkIf('B').then(function(bool) {
            if (bool)
                return 'B';
            return checkIf('C').then(function(bool) {
                if (bool)
                    return 'C';
                throw new Error();
            });
        });
    });
}

没有 if else - 承诺中的讨论。

There is no if else-flattening in promises.

这篇关于如何打破承诺链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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