首页 > 文章列表 > Promisefinally():让 Promise 更顺畅的秘密武器

Promisefinally():让 Promise 更顺畅的秘密武器

160 2024-12-10

Promisefinally():让 Promise 更顺畅的秘密武器

当你有一个承诺时,有时你想确保某些代码始终运行,无论承诺的结果如何。例如,您可能想要隐藏加载微调器或关闭文件连接,无论操作是否成功。在 finally() 之前,开发人员必须在 .then() 和 .catch() 块中复制代码。 finally() 消除了冗余。

fetchData()
  .then((data) => {
    console.log('Data fetched successfully', data);
  })
  .catch((error) => {
    console.error('Error fetching data', error);
  })
  .finally(() => {
    hideLoadingSpinner(); // Runs no matter the result
  });
来源:https://dev.to/elukuro/promisefinally-your-secret-weapon-for-smoother-promise-2djk

本类最新

查看更多