【问题标题】:How to use Promise.prototype.finally() in async/await syntax?如何在异步/等待语法中使用 Promise.prototype.finally()?
【发布时间】:2018-10-26 15:40:27
【问题描述】:

实际上我的主要问题是在async/await ES8 语法中使用Promise.prototype.catch(),毫无疑问Promise.prototype.then() 存在于async/await 语法的本质中。

我在async/await 中搜索了有关使用Promise.prototype.catch() 的信息,发现:

async () => {
  try {
    const result1 = await firstAsynchronousFunction();
    const result2 = await secondAsynchronousFunction(result1);
    console.log(result2);
  } catch(err) {
    throw new Error(`Something failed`);
  }
}

而且我绝对知道Promise 链接,例如:

new Promise((resolve) => {
  console.log(`Initial`);
  resolve();
})
.then(() => {
  console.log(`Task Number One`);
})
.catch(() => {
  console.log(`Task in Error`);
})
.finally(() => {
  console.log(`All Tasks is Done`);
})

所以,我的问题是如何在async/await 语法中使用finally

【问题讨论】:

    标签: javascript asynchronous async-await ecmascript-2017


    【解决方案1】:

    这应该可行:

    async () => {
      try {
        const result1 = await firstAsynchronousFunction();
        const result2 = await secondAsynchronousFunction(result1);
        console.log(result2);
      } catch(err) {
        throw new Error(`Something failed`);
      } finally {
        console.log(`All Tasks is Done`);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      相关资源
      最近更新 更多