如何打破承诺链

mid*_*ido 12 javascript promise selenium-chromedriver selenium-webdriver

我是这样的承诺,

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;
}
Run Code Online (Sandbox Code Playgroud)

checkIf返回一个promise,是的checkIf ,无法修改.

我如何在第一场比赛中脱颖而出?(除了明确抛出错误之外的任何其他方式?)

vil*_*ane 14

除了明确抛出错误之外的任何方式?

你可能需要抛出一些东西,但它不一定是错误的.

大多数promise实现都有catch接受第一个参数作为错误类型的方法(但不是全部,而不是ES6的承诺),在这种情况下它会有所帮助:

function BreakSignal() { }

getPromise()
    .then(function () {
        throw new BreakSignal();
    })
    .then(function () {
        // Something to skip.
    })
    .catch(BreakSignal, function () { })
    .then(function () {
        // Continue with other works.
    });
Run Code Online (Sandbox Code Playgroud)

我添加了破解我自己的promise库的最近实现的能力.如果你使用的是ThenFail(你可能没有),你可以写下这样的东西:

getPromise()
    .then(function () {
        Promise.break;
    })
    .then(function () {
        // Something to skip.
    })
    .enclose()
    .then(function () {
        // Continue with other works.
    });
Run Code Online (Sandbox Code Playgroud)


小智 9

您可以使用 return { then: function() {} };

.then(function(bool){
    if(bool){
        deferred.resolve('A');
        return { then: function() {} }; // end/break the chain
    }else{
        return checkIf('B');
    }
})
Run Code Online (Sandbox Code Playgroud)

return 语句返回一个“then-able”,只是 then 方法什么都不做。当从 then() 中的函数返回时, then() 将尝试从 thenable 中获取结果。then-able 的“then”接受一个回调,但在这种情况下永远不会被调用。因此“then()”返回,并且不会发生链其余部分的回调。


Ber*_*rgi 3

我想你不想要这里的链条。以同步的方式,你会写

function getMode(){
    if (checkIf('A')) {
        return 'A';
    } else {
        if (checkIf('B')) {
            return 'B';
        } else {
            if (checkIf('C')) {
                return 'C';
            } else {
                throw new Error();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这就是它应该如何翻译为承诺:

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();
            });
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

承诺中不存在if else扁平化。

  • auti 模式之一:t​​hen 包括 then (3认同)