簡體   English   中英

如何打破多個Ajax承諾鏈?

[英]how to break multiple Ajax promise chain?

我有多個ajax請求一起工作,並且每個請求都基於前一個請求的結果,如果前一個請求返回false,則鏈應該停止。

這是一些代碼

 //here is a promise chain    

 return this.getBand(id)
            .then(this.getAlbum)
            .then(this.getSong);
//ajax request for getBand
function getBand(id) {
  return Ember.$.ajax({
    data:{id: id},
    url: urls.bandUrl,
  }).then(function(result){
    return result;
  });
};

//ajax request for getAlbum
function getAlbum(result){
  if(result.pass) {
  var bandName = result.name;
  return Ember.$.ajax({
   //...
  })
  } else {
  // i wanna stop the promise chain here, how to do that?
  }
}

您可以通過返回拒絕的Deferred來指示鏈中的錯誤:

function getAlbum(result) {
  if (result.pass) {
    // ...
  } else {
    return Ember.$.Deferred().reject('Previous result did not pass');
  }
}

您還可以修改getBand()來檢查result.pass本身,因此,除非成功通過,否則不會調用getAlbum()

function getBand(id) {
  return Ember.$.ajax({
    // ...
  }).then(function(result){
    return result.pass ?
      result :
      Ember.$.Deferred().reject('Band could not be found (' + id + ').');
  });
};

鏈條不會完全停止,但它只會繼續到fail回調/過濾器,提供給.then()作為第二參數或.fail()

return this.getBand(id)
    .then(this.getAlbum)
    .then(this.getSong)
    .fail(function (error) {
        // show `error` to user
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM