【问题标题】:how to break multiple Ajax promise chain?如何打破多个 Ajax 承诺链?
【发布时间】:2015-08-21 02:45:10
【问题描述】:

我有多个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?
  }
}

【问题讨论】:

    标签: javascript ajax ember.js promise


    【解决方案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 回调/过滤器,作为第二个参数提供给.then().fail()

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

    【讨论】:

    • 做 `Ember.$.Deferred().reject(...)` 非常愚蠢,最好使用 ember 本身使用 RSVP 承诺发出 ajax 请求,这会让你@987654333 @.
    猜你喜欢
    • 2017-11-23
    • 2020-02-23
    • 2019-05-10
    • 1970-01-01
    • 2015-06-12
    • 2016-09-03
    相关资源
    最近更新 更多