假设抛出then()
次回调失败地拒绝了结果promise ,而从then()
次回调返回则实现了结果promise 的成功值.
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 就没有用处.
这并不意味着在你的例子中p2
会是become p3
.它们是不同的promise 对象.然而,如果从then()
返回p2
,产生p3
,你就是说“I want 101 to resolve to whatever 100 resolves, whether it succeeds or fails”.
对于how来说,这种情况是特定于实现的.在内部,你可以认为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的解析.在你对这个 idea 感到满意之后,我建议你看看实际的promise 是如何实现的.