javascript - 我将如何将使用 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));
});
}
解决方案
让 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;
}
推荐阅读
- html - 如何删除 span 标签生成的空格?
- python - Python 在继续第二个循环的同时打破了两个同时循环的一个循环
- c - 如何从 switch 语句中获取跳转表的案例编号
- react-native - *%#:& 的正则表达式在本机反应中包括空格?
- linux - 带单引号和双引号的动态 shell 脚本
- amazon-web-services - sendmail 不记录,不发送邮件
- coq - 软件基础第 1 卷:策略:injection_ex3
- python - Python - 为相同/或不同数据帧/秒内的多个回归创建一个 For 循环
- java - 如何模拟双自动装配类
- ruby-on-rails - 我正在使用 POST 方法将文件传输到给定的 URL,并在 rails 中出现错误