【问题标题】:How does Promise chain work when one callback doesn't return any promise?当一个回调没有返回任何承诺时,Promise 链如何工作?
【发布时间】:2021-01-13 08:54:34
【问题描述】:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

当 .then() 缺少返回 Promise 对象的适当函数时,处理只是继续到链的下一个链接。因此,链可以安全地省略每个 handleRejection 直到最后的 .catch()。同样,.catch() 实际上只是一个 .then(),没有用于 handleFulfilled 的槽。

考虑:

promise.then()、promise.catch() 和 promise.finally() 方法用于将进一步的操作与已确定的 Promise 相关联。这些方法还返回一个新生成的 Promise 对象,可以选择用于链接;

当一个回调没有返回任何承诺时,Promise 链如何工作?

【问题讨论】:

  • 链上的 Promise 会捕获任何异常,如果它拦截到一个异常,它将使其“失败”,如果它接收到任何其他值,它将使其“成功”。跨度>
  • 那句话“When a .then() lacks the appropriate function”并不是指你的回调没有返回promise的情况,而是指您没有传入回调,例如 .then(onFulfilled, null).then(null, onRejected).then(null, null)
  • @Bergi 内容丰富。谢谢你。请写一个答案。
  • “当 .then() 缺少 ....”段落不是最好的。我不确定我是否想从中学习 Promises。

标签: javascript node.js promise


【解决方案1】:

如果 Promise 链返回一个 Promise,它将使用该 Promise 的已解决(或拒绝)值调用下一个 then(或 catch)。如果没有,那么它将使用返回的值调用下一个then(如果没有返回值,则调用undefined):

const myPromise = myApiCall().then(response => {
   return anotherApiCallThatReturnsAPromise(response);
}).then(secondResponse => {
   // this is the resolved value of anotherApiCall...
   return secondResponse;
}).catch(err => {
 // this error could be because myApiCall failed or because anotherApiCall... failed
})
const myPromise = myApiCall().then(response => {
   return 42
}).then(value => {
   // value is 42
}).catch(err => {
 // this error, if present, is because myApiCall failed
}) 

推断,让我们从第一个回调中不返回任何内容:

const myPromise = myApiCall().then(response => {
   // notice we do not return anything here
   // we just call a function - i.e. return undefined
   doSomeWorkAndReturnNothing();
}).then(value => {
   // value is undefined because nothing was returned from the previous `then`
}).catch(err => {
 // this error, if present, is because myApiCall failed
}) 

只是为了好玩,下面是在 async 函数中使用 await 的样子:

const myFunc = async () => {
   try {
     const response = await myApiCall();
     const secondResponse = await anotherApiCallThatReturnsAPromise(response);
     return secondResponse;
   } catch(err) {
     // this error could be because either of the previous two await-ed calls failed
   }

}

【讨论】:

    猜你喜欢
    • 2015-11-27
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2017-12-20
    • 2016-01-04
    • 2017-05-09
    相关资源
    最近更新 更多