假设在
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对象。然而,通过返回
p2从
then()产生
p3你说
“我想要
p3解析到任何
p2议决,无论成功或失败”。
至于这种情况 如何
发生,则取决于具体实现。在内部,您可以将其
then()视为创建新的Promise。该实现将能够在需要时实现或拒绝它。通常,当您返回时,它将自动实现或拒绝它:
// Warning: this is just an illustration// and not a real implementation pre.// 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 pre 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 })}
同样,这是非常伪的代码,但显示了如何
then()在Promise实现中实现的背后思想。
如果我们想增加对解决Promise的支持,我们只需要修改代码以
callback在
then()返回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实现如何处理此问题。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)