【问题标题】:How to resolve multiple then() promise into one如何将多个 then() 承诺合二为一
【发布时间】:2021-03-05 21:35:09
【问题描述】:

在这段代码中我使用了多个then() 方法,我只想将它转换为一个,这怎么可能。

getGreeting = () => {
  fetch(url)
    .then((response) => response.json())
    .then((result) => result.data)
    .then((data) => printCards(data))
    .catch((err) => {
      console.log(err);
    });
};

【问题讨论】:

  • 这个解决方案有什么问题?它看起来干净易读
  • 这是一个很好的解决方案,不应更改。不过,可以通过将 .then((data) => printCards(data)) 更改为 .then(printCards) 来改进它,这是相同的
  • 我认为第二个 then 块没有返回 Promise。你可以在两个然后块而不是三个块中完成它。
  • 如果我使用 async 和 await 是否是多个 then() 方法的好选择?

标签: javascript node.js promise fetch


【解决方案1】:

注意 asyncawait 关键字

fetch(url)
    .then(async (response) => {
      const json = await response.json();
      printCards(json.data);
     })
    .catch((err) => {
      console.log(err);
    });
};

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2015-01-14
    • 1970-01-01
    • 2016-12-25
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多