承诺回调返回承诺

承诺回调返回承诺,第1张

承诺回调返回承诺

假设在

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实现如何处理此问题。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5087927.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存