只要promise的结果还没有被解决,它就总是记录挂起的日志。你必须在promise上调用.then来捕获结果,而不管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"
})
为什么呢?
承诺只是前进的方向;你只能解决一次。Promise的解析值被传递给它的.then或.catch方法。
细节
根据承诺/A+规范:
The promise resolution procedure is an abstract operation taking as
input a promise and a value, which we denote as [[Resolve]](promise,
x). If x is a thenable, it attempts to make promise adopt the state of
x, under the assumption that x behaves at least somewhat like a
promise. Otherwise, it fulfills promise with the value x.
This treatment of thenables allows promise implementations to
interoperate, as long as they expose a Promises/A+-compliant then
method. It also allows Promises/A+ implementations to “assimilate”
nonconformant implementations with reasonable then methods.
这个规范有点难以解析,所以让我们详细分析一下。规则是:
如果.then处理程序中的函数返回一个值,则Promise解析该值。如果处理程序返回另一个Promise,则原始Promise将使用链接的Promise的已解析值进行解析。下一个.then处理程序将始终包含在前一个.then中返回的链式承诺的解析值。
它的实际工作方式如下所述:
1. then函数的返回值将是承诺的解析值。
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函数返回一个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"
});