有条件的有条件承诺

Jer*_*odi 6 promise angularjs angular-promise

对于一个有角度的项目,我必须嵌套承诺,我遇到了我不确定我在做什么的情况.这是我的一个代码:

return Action1().then(function (data) {
    var defer = $q.defer();
    if (data.condition) {
        $q.all([Action2(), Action3(), Action4()]).then(function () {
            defer.resolve();
        });
    } else {
        defer.reject("error_code");
    }
    return defer.promise;
});
Run Code Online (Sandbox Code Playgroud)

Action1,Action2,Action3和Action4正在使用promises函数.这是很多承诺和行动取决于条件.我可以这样做,并确保我的主要功能将始终被解决或拒绝?

我读到我们可以在promise函数中传递promise.我可以这样做,这与上面相同:

return Action1().then(function (data) {
    var defer = $q.defer();
    if (data.condition) {
        defer.resolve($q.all([Action2(), Action3(), Action4()]);
    } else {
        defer.reject("error_code");
    }
    return defer.promise;
});
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 3

不它不是。如果或之一“抛出”,并且拒绝Action2()承诺,您的第一个函数将永远处于待处理状态- 那么您的延迟永远不会得到解决。这是您在此处使用的延迟反模式的最常见错误。Action3()Action4()$q.all(\xe2\x80\xa6)

\n\n

你的第二个函数确实缓解了这个问题,但仍然没有必要复杂。你根本不需要在这里延期!只需直接返回承诺,然后使用$q.reject

\n\n
return Action1().then(function (data) {\n    if (data.condition) {\n        return $q.all([Action2(), Action3(), Action4()]);\n    } else {\n        return $q.reject("error_code");\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者,当这发生在then处理程序内部时,您也可以使用throw "error_code".

\n