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

时间:2014-12-16 14:40:14

标签: angularjs

我有一个多步骤的过程,我想找到一个更好的模式。假设您需要创建收入记录以便最终准备发票。我有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)

当然每个人都必须具有失败功能,并且它变得相当难看。我知道$ q.defer可以让我合并promises并且只有在完成时才返回,但是这个过程需要步骤顺序。我想知道是否有更好的模式来解决涉及回调的多步顺序过程。

2 个答案:

答案 0 :(得分:0)

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

假设您的所有异步调用都返回了一个promise,链接将如下所示:

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
  }

答案 1 :(得分:0)

我认为这是一个大多数“行动”都是服务器端的情况,我应该在那里做这件事。我创建了新的API路线,用于添加收入/费用行,捆绑了发票详细信息并在那里处理了75%。更简单,新的API调用可能会在未来的其他地方使用。