只要其结果尚未解决,promise 将始终记录挂起。.then
无论Promise状态如何(已解决或仍在等待),您都必须调用Promise来捕获结果:
let AuthUser = function(data) {
return google.login(data.username, data.password).then(token => { return token } )
}
let userToken = AuthUser(data)
console.log(userToken) // Promise { <pending> }
userToken.then(function(result) {
console.log(result) // "Some User token"
})
这是为什么?
Promises 只是向前的;您只能解决一次。a 的解析值Promise
传递给它的.then
或.catch
方法。
细节
根据 Promises/A+ 规范:
Promise解析过程是一个抽象操作,将Promise和值作为输入,我们将其表示为 [[Resolve]](promise, x)。如果 x 是一个 thenable,它会尝试让 promise 采用 x 的状态,假设 x 的行为至少有点像 promise。否则,它以值 x 履行Promise。
对 thenables 的这种处理允许 promise 实现互操作,只要它们公开一个符合 Promises/A+ 的 then 方法。它还允许 Promises/A+ 实现用合理的 then 方法“同化”不一致的实现。
这个规范有点难以解析,所以让我们分解一下。规则是:
如果.then
处理程序中的函数返回一个值,则Promise
使用该值进行解析。如果处理程序返回另一个Promise
,则原始处理程序Promise
使用链式 的已解析值进行解析Promise
。下一个.then
处理程序将始终包含前一个 中返回的链式Promise的解析值.then
。
下面更详细地描述了它的实际工作方式:
1..then
函数的返回值是promise 的解析值。
function initPromise() {
return new Promise(function(res, rej) {
res("initResolve");
})
}
initPromise()
.then(function(result) {
console.log(result); // "initResolve"
return "normalReturn";
})
.then(function(result) {
console.log(result); // "normalReturn"
});
2. 如果.then
函数返回 a Promise
,则该链式 promise 的已解析值将传递给以下.then
。
function initPromise() {
return new Promise(function(res, rej) {
res("initResolve");
})
}
initPromise()
.then(function(result) {
console.log(result); // "initResolve"
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("secondPromise");
}, 1000)
})
})
.then(function(result) {
console.log(result); // "secondPromise"
});