Angularjs 多个顺序回调的最佳模式?

Angularjs 多个顺序回调的最佳模式?,angularjs,Angularjs,我有一个多步骤的过程,我想找到一个更好的模式。假设有一个订单,您需要为其创建收入记录,以便最终准备发票。我有4个回调函数调用,需要按顺序调用。回调通常与此处的回调类似: getRevenue(item.ID, function(revenueRecords) //on success {..do whatever to revenue here...}, function(errorMsg) //on failure {..show error msg here...});

我有一个多步骤的过程,我想找到一个更好的模式。假设有一个订单,您需要为其创建收入记录,以便最终准备发票。我有4个回调函数调用,需要按顺序调用。回调通常与此处的回调类似:

getRevenue(item.ID,
  function(revenueRecords) //on success
  {..do whatever to revenue here...}, 
  function(errorMsg) //on failure
  {..show error msg here...});
所以在我的代码中,我需要这样的4个:

  getRevenue
    getNewInvoice#
      (create invoice details)
      saveRevenue
        (mark order as billed)
        saveOrder
          (alert user we succeeded)
getRevenue(item.ID)
  .then(function(revenueRecords){
     //..do whatever to revenue here...
     return getNewInvoiceNum(record)
  }
  .then(function(invoiceNum){
     //..create invoice details...
     return saveRevenue()
  }
  .then(function(invoiceNum){
     //..mark order as billed...
     return saveOrder();
  }
  .then(function(isSuccess)){
     //..alert user we succeeded...
  }
  .catch(function(error)){
     // deal with any `rejects` that could happen
  }

当然,每一个都必须有一个失败的功能,它变得非常丑陋。我知道$q.defer可以让我组合承诺,并且只有当它们全部完成时才返回,但是这个过程要求步骤是顺序的。我想知道是否有更好的模式来解决涉及回调的多步骤顺序流程。

您可以为顺序处理链接承诺:

假设所有异步调用都返回一个承诺,链接将如下所示:

  getRevenue
    getNewInvoice#
      (create invoice details)
      saveRevenue
        (mark order as billed)
        saveOrder
          (alert user we succeeded)
getRevenue(item.ID)
  .then(function(revenueRecords){
     //..do whatever to revenue here...
     return getNewInvoiceNum(record)
  }
  .then(function(invoiceNum){
     //..create invoice details...
     return saveRevenue()
  }
  .then(function(invoiceNum){
     //..mark order as billed...
     return saveOrder();
  }
  .then(function(isSuccess)){
     //..alert user we succeeded...
  }
  .catch(function(error)){
     // deal with any `rejects` that could happen
  }

我决定在这种情况下,大多数“操作”都是服务器端的,我真的应该在那里做。我创建了新的API路线,用于添加收入/支出行,捆绑了发票详细信息,并在那里处理了75%的发票。更简单,新的API调用将来可能会在其他地方使用。

请看:从这个角度尝试看起来很简单,但我想我的问题是,如果出现错误,我希望在每个步骤中都有一些有用的反馈,并且我在每个成功区域都有几行处理。当您将这些添加到上面的链中时,就可读性而言,并不比异步版本好多少。我想我希望有一个像q.all()这样的神奇解决方案来组合承诺。区别在于
.catch
捕获所有拒绝。返回的“拒绝”会导致级联拒绝。