如何在async / await语法中使用Promise.prototype.finally()?

时间:2018-05-16 14:15:03

标签: javascript asynchronous async-await ecmascript-2017

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

我在Promise.prototype.catch()中使用async/await进行了搜索,发现了这个:

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`);
})

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

1 个答案:

答案 0 :(得分:9)

这应该有效:

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`);
  }
}