如何打破多个Ajax承诺链?

时间:2022-06-28 20:34:08

I have multiple ajax request working together, and each request based on previous request's result, if the previous request return false, the chain should stops.

我有多个ajax请求一起工作,并且每个请求都基于前一个请求的结果,如果前一个请求返回false,则链应该停止。

Here's some code

这是一些代码

 //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 个解决方案

#1


1  

You can indicate an error in the chain by returning a rejected Deferred:

您可以通过返回被拒绝的Deferred来指示链中的错误:

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

You can also revise getBand() to check result.pass itself, so getAlbum() won't be invoked unless it did 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 + ').');
  });
};

The chain won't completely stop, but it will only proceed to fail callbacks/filters, provided to .then() as a 2nd argument or .fail().

链不会完全停止,但它只会进入失败的回调/过滤器,提供给.then()作为第二个参数或.fail()。

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

#1


1  

You can indicate an error in the chain by returning a rejected Deferred:

您可以通过返回被拒绝的Deferred来指示链中的错误:

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

You can also revise getBand() to check result.pass itself, so getAlbum() won't be invoked unless it did 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 + ').');
  });
};

The chain won't completely stop, but it will only proceed to fail callbacks/filters, provided to .then() as a 2nd argument or .fail().

链不会完全停止,但它只会进入失败的回调/过滤器,提供给.then()作为第二个参数或.fail()。

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