假设在then()回调中抛出一个失败的结果承诺,并从then()回调返回一个成功的结果承诺。
let p2 = p1.then(() => {
throw new Error('lol')
})
// p2 was rejected with Error('lol')
let p3 = p1.then(() => {
return 42
})
// p3 was fulfilled with 42
但有时,即使在延续中,我们也不知道我们是否成功。我们需要更多时间。
return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
// I want to do some async work here
})
但是,如果我在那里进行异步工作,那么 return 或 throw 就太晚了,不是吗?
return checkCache().then(cachedValue => {
if (cachedValue) {
return cachedValue
}
fetchData().then(fetchedValue => {
// Doesn’t make sense: it’s too late to return from outer function by now.
// What do we do?
// return fetchedValue
})
})
这就是为什么如果你不能解决另一个 Promise,Promise 就没有用处。
这并不意味着在您的示例中 p2 会变成 p3。它们是独立的 Promise 对象。但是,通过从产生p3 的then() 返回p2,您是在说“我希望p3 解析为p2 解析的任何内容,无论它成功还是失败”。 p>
至于如何发生这种情况,这是特定于实现的。在内部,您可以将then() 视为创建一个新的 Promise。实现将能够随时满足或拒绝它。通常情况下,它会在您返回时自动履行或拒绝:
// Warning: this is just an illustration
// and not a real implementation code.
// For example, it completely ignores
// the second then() argument for clarity,
// and completely ignores the Promises/A+
// requirement that continuations are
// run asynchronously.
then(callback) {
// Save these so we can manipulate
// the returned Promise when we are ready
let resolve, reject
// Imagine this._onFulfilled is an internal
// queue of code to run after current Promise resolves.
this._onFulfilled.push(() => {
let result, error, succeeded
try {
// Call your callback!
result = callback(this._result)
succeeded = true
} catch (err) {
error = err
succeeded = false
}
if (succeeded) {
// If your callback returned a value,
// fulfill the returned Promise to it
resolve(result)
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
// then() returns a Promise
return new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
}
同样,这是非常伪代码,但展示了如何在 Promise 实现中实现 then() 背后的想法。
如果我们想要添加对 Promise 解析的支持,我们只需要修改代码以在你传递给 then() 的 callback 返回一个 Promise 的情况下拥有一个特殊的分支:
if (succeeded) {
// If your callback returned a value,
// resolve the returned Promise to it...
if (typeof result.then === 'function') {
// ...unless it is a Promise itself,
// in which case we just pass our internal
// resolve and reject to then() of that Promise
result.then(resolve, reject)
} else {
resolve(result)
}
} else {
// If your callback threw an error,
// reject the returned Promise with it
reject(error)
}
})
让我再次澄清一下,这不是一个实际的 Promise 实现,并且存在很大的漏洞和不兼容性。但是,它应该让您直观地了解 Promise 库如何实现对 Promise 的解析。在你对这个想法感到满意之后,我建议你看看实际的 Promise 实现如何handle this。