javascript - 如何改变 promise 链?

标签 javascript jquery promise jquery-deferred

在 promise 链中,有没有办法让其中一个成员将 promise 添加到链中?

这段代码更好地说明了我的意思:

$.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 Promise 没有太多经验,但你绝对可以用另一个 Promise 来支付 Promise,就像 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!'))

我希望您可以根据您的需求进行调整,或者可以使用原生的 Promise。

关于javascript - 如何改变 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918803/

相关文章:

javascript - 使用参数执行 Promise.all

javascript - 在 JavaScript 中使用 001 作为数字与 1 相同吗?

javascript - 使用ajax登录时如何让浏览器提示保存密码

提交表单时的 Javascript 转换?

javascript - NodeJS 何时使用 promise ?

javascript - easeljs 旋转容器离开屏幕

javascript - Node Webkit - 另存为对话框,在 "Save as Type"字段上有多个选项

javascript - 查询;检查对象是否有子 $(this)

javascript - Firebase 实时数据库 - 没有嵌套 promise 的多个顺序获取和写入操作

javascript - 有没有办法判断 ES6 promise 是否已履行/拒绝/解决?