在 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/