2015-06-06 69 views
0

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

下面是一些代碼

//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? 
    } 
} 

回答

1

您可以通過返回表示鏈中的一個錯誤rejected 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回調/過濾器,提供給​​作爲第二參數或.fail()

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

做'灰燼。$。遞延()。拒絕(...)'是非常愚蠢的,這是更好的使用RSVP承諾which'd讓你'throw'使用燼本身Ajax請求作出。 –