首页 > 解决方案 > 我将如何将使用 fetch 调用的函数转换为 async/await?

问题描述

我将如何将其转换为使用 async/await 而不是 fetch?抱歉,我对这个主题真的很困惑,非常感谢一些帮助。

coreHTTP.prototype.post = (url, data) => {
  return new Promise((resolve, reject) => {
    fetch(url, {
      method: "POST",
      headers: {"content-type": "application/json"},
      body: JSON.stringify(data)
    })
      .then(res => res.json())
      .then(data => resolve(data))
      .catch(err => reject(err));
  });
}

标签: javascriptasynchronous

解决方案


让 fetch 保持原样怎么样?如果您只想使用 awaits,那么它就没有问题。

coreHTTP.prototype.post = async (url, data) => {
    const responseData = await fetch(url, {
      method: "POST",
      headers: {"content-type": "application/json"},
      body: JSON.stringify(data)
    });

    const responseJson = await responseData.json();
    return responseJson;
}

推荐阅读