2016-10-02 94 views
0

我需要得到四個響應的承諾,但要做到這一點,我首先必須按順序調用每個函數,從第一個到最後一個。您可以從我的代碼中看到,我從最後一次調用的函數的promise回調中調用下一個函數。順序承諾

但代碼看起來不合適,所以我需要知道是否有一些更好的方法來做到這一點。

有什麼建議嗎?

$scope.createPayment = function() { 
    var dados = $scope.card; 
// get first promise 
    PagamentoMP.createToken(dados) 
    .then(
     function(result) { 
      dados.token = result; 
// get second promise 
      PagamentoMP.guessPaymentMethod(dados) 
      .then(
       function(result) { 
        dados.paymentMethod = result; 
// get third promise    
        PagamentoMP.getIssuers(dados) 
        .then(
         function(result) { 
          dados.issuer = result; 
// get fourth promise 
          PagamentoMP.getInstallments(dados) 
          .then(
           function(result) { 
            dados.installments = result;  
           }, 
// error for fourth promise 
           function(result) { 
            console.log("getInstallments PAGAMENTOMP -> Failed to get the name, result is " + result); 
           } 
          ); 
         }, 
// error for third promise      
         function(result) { 
          console.log("getIssuers PAGAMENTOMP -> Failed to get the name, result is " + result); 
         }); 
        }, 
// error for second promise     
        function(result) { 
         console.log("guessPaymentMethod PAGAMENTOMP -> Failed to get the name, result is " + result); 
        }); 
       }, 
// error for first promise    
      function(result) { 
       console.log("createToken PAGAMENTOMP -> Failed to get the name, result is " + result); 
      }); 
    }; 
+1

我不知道你是否有任何控制返回承諾的函數。如果你這樣做,我會考慮改造它們,這樣你可以避免這麼多的異步的東西。如果我必須不止一次地用承諾套巢,我總是在考慮一面紅旗。 –

回答

1

而不是做這個的,

a().then(function(result) { 
    b(result).then(function(result) { 
     c(result).then(function(result) { 
      console.log("done"); 
     }); 
    }); 
}); 

您可以鏈接所有承諾在頂層。

a() 
    .then(function(result) { 
     return b(result); 
    }) 
    .then(function(result) { 
     return c(result); 
    }) 
    .then(function(result) { 
     console.log("done"); 
    }); 

這樣的模式可以在你的代碼中使用。

要捕獲錯誤,請在鏈的末尾添加.catch,如果您希望鏈中所有錯誤都有一個錯誤處理程序。

a() 
    .then(function(result) { 
     console.log("done"); 
    }) 
    .catch(function(err) { 
     console.error(err); 
    }); 

對於每一步單獨的錯誤處理,你可以做這樣的事情:

a() 
    .catch(function(err) { 
     console.log("error in a"); 
     throw err; 
    }) 
    .then(function(result) { 
     return b() 
      .catch(function(err) { 
       console.log("error at b"); 
       throw err; 
      }); 
    }) 
    .then(function(result) { 
     return c() 
      .catch(function(err) { 
       console.log("error at c"); 
       throw; 
      }); 
    }); 

每個錯誤處理程序需要調用throw這樣,當發生錯誤的時候它不會繼續環比下滑。

+0

非常感謝你@afuous 錯誤響應呢?我如何獲得並處理它? – vinoli

+0

@vinoli查看我的編輯 – afuous

+0

好吧,但如果我想爲每個響應獲取單獨的錯誤消息? – vinoli