如何改变一个承诺链

How to alter a promise chain?

本文关键字:一个承诺 改变 何改变      更新时间:2023-09-26

在承诺链中,是否有任何方法可以让其中一个成员将承诺添加到链中?

下面的代码更好地说明了我的意思:

$.ajax(......).then(function(r){
  .....
  return r;
}).then(function(r){
  var d = $.Deferred();
  // how to add d.promise() to this chain ?
  ....
  return r;
}).then(function(r){
  // this function should be able to receive "r"
  // but should also wait for the promise above to complete :(
  ....
});

我对jQuery承诺没有太多的经验,但是你肯定可以用另一个承诺来支付一个承诺,就像Nicolas Bevacqua在Ponyfoo文章ES6 promises in Depth中解释的那样。

var p = Promise.resolve()
  .then(data => new Promise(function (resolve, reject) {
    setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
  }))
p.then(data => console.log('okay!'))
p.catch(data => console.log('boo!'))

我希望你能适应你的需要,或者使用原生的承诺。

.then()返回r,在$.Deferred() beforeStart函数中使用带参数r.resolve(),从.then()返回d.promise(),使r在链中的下一个.then()可访问

 .then(function(r) {
  .....
    var d = $.Deferred(function(dfd) {
      // do stuff
      dfd.resolve(r)
    });
    // how to add d.promise() to this chain ?
    ....
    return d.promise();
 })

$.when(1).then(function(r) {
  return r;
}).then(function(r) {
  var d = $.Deferred(function(dfd) {
    
    // do stuff
    setTimeout(function() {
      dfd.resolve(r)
    }, Math.random() * 2500)
  });
  // how to add d.promise() to this chain ?
  //....
  return d.promise();
})
.then(function(r) {
  console.log(r)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>