如何构建模块化的 js 承诺链?

How to build modular js promise chains?

我有一个承诺链,目前是 运行 非常基本的错误处理。如果一个步骤失败,则后续步骤将不会运行。如果出现故障,我希望能够在以后继续 promise 链,并且它应该从它停止的地方开始。

这就是我当前的代码:

// controller.js
var failure = false;
QueryFactory.step1()                      // Step 1
   .then(function(msg){
      if(failure == false){
        console.log("Finished Step 1");
        return QueryFactory.step2();
      }
   }, function(err){
      console.log(err);
      failure = true;
   })
   .then(function(msg){                   // Step 2
      if(failure == false){
         console.log("Finished Step 2");
         return QueryFactory.step3();
      }
   }, function(err){
      console.log(err);
      failure = true;
   })
   .then(function(msg){                   // Step 3
      if(failure == false){
         console.log("Finished Step 3");
      }
   }, function(err){
      console.log(err);
      failure = true;
   })

我的工厂是这样的:

// QueryFactory.js
step1 = function(){
   var deferred = $q.defer();
   $http.post('/task', {step_num: 1})
      .then(function(data)){
         deferred.resolve(data);
      }, function(err){
         deferred.reject(err);
      });
   return deferred.promise;
}
// step2 and step3 are similar

但也许有更好的写法来实现模块化?假设 step2 失败了,我如何设计一种方法,以便用户可以单击按钮稍后从 step2 继续链?

看看difference between .then(…).catch(…) and .then(…, …)。在您的例子中,通过将第二个回调传递给 then,您最终将跳过当前步骤,而不是从您离开的地方继续。您要找的是

QueryFactory.step1()
.then(function(msg) {
    console.log("Finished Step 1 without error");
    return msg;
}, function(err) {
    console.log(err);
    …
}).then(function() {
    return QueryFactory.step2();
}).then(function(msg) {
    console.log("Finished Step 2 without error");
    return msg;
}, function(err) {
    console.log(err);
    …
}).then(function() {
    return QueryFactory.step3();
}).then(function(msg) {
    console.log("Finished Step 3 without error");
    return msg;
}, function(err) {
    console.log(err);
    …
}).then(function(res) {
    console.log("everything is finished");
}).catch(function(err){
    console.error("something bad happened", err);
});

(或者,如果您不需要这些日志,您可以使用带有回调的普通 .catch 而不是 then,回调告诉您步骤是否正确完成)

现在,代码中的这些 是什么?满足您的要求

I want to be able to continue the promise chain at a later time if there is a failure

部分,您将需要 处理 错误,并且 return 承诺失败步骤的无错误结果,例如通过重试。这个 promise 只会在那 "later time" 时解决——您可以等待用户确认错误、超时或任何您想要的。

一旦您从错误回调中 return 得到承诺,链将继续。