【发布时间】:2016-07-15 07:40:01
【问题描述】:
我使用过 $q (Angular.js) 并且经常会在 .then 调用中返回承诺。结果是下一个.then 调用将等待前一个promise 完成。
我现在正在使用本机 es6 承诺尝试“承诺”基于回调的库,但我无法这样做。
问题在于.then 链中的下一个值是一个promise 对象,而不是该promise 的已解决值。它在 promise 被解析之前调用下一个 .then 值,只是返回最后一个返回值。
还有没有等待之前的promise解决?
例子:
$.ajax({
url: "//localhost:3000/api/tokens",
type: "POST",
data: JSON.stringify({
user: {
email: 'admin@admin.com',
password: 'password123'
}
}),
contentType: "application/json"
})
.then(data => data.token.encoded) // OK
.then(token => Farmbot({ token: token })) // OK
.then(function(bot){ // OK
return new Promise(function(resolve, reject) {
bot.connect(function(){ resolve(bot); });
});
}, errorr)
.then(function(bot){ // NOT OK!
// passes in an unresolved promise object, which is useless.
//
bot; // => {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
});
我的问题是:
ES6 Promise 会等待之前的 .then 的 Promise 解决吗?
【问题讨论】:
-
Angular 和 jQuery 并不是特别好的伙伴。在 Angular 应用程序中,您应该真正使用
$http(),而不是jQuery.ajax()
标签: javascript jquery angularjs promise ecmascript-6