首页 > 解决方案 > 如何将多个 then() 承诺合二为一

问题描述

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

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

标签: javascriptnode.jspromisefetch

解决方案


注意asyncawait关键字

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

推荐阅读