node.js - 如何在使用 fetch 的 post/get 请求中使用 await?
问题描述
我有以下代码有效,但我不喜欢使用
await new Promise(resolve => setTimeout(resolve, 10000));
我想以第二次调用真正等到第一次调用的结果准备好的方式更改我的代码。在当前代码中,如果我删除上面的代码,我无法从第二次调用中获得预期的结果。我还应该提到,每次调用需要大约 5-8 秒来准备输出。
const url = "myUrl";
let bodyText = JSON.stringify({ data: dataResult});
await fetch(url, {
method: "POST",
headers: { 'Content-Type': 'application/json', 'header': 'myHeader'},
body: bodyText
}).then(async postres=> {
if (!postres.ok) {
console.log("error1");
}
if (postres.ok) {
console.log("success1");
}
await new Promise(resolve => setTimeout(resolve, 10000));
return await fetch(postres.headers.get("something"), {
method: "GET",
headers: { 'header': 'myHeader'}
});
}).then(async getres=> {
if (!getres.ok) {
console.log("error2");
}
if (getres.ok) {
console.log("success2");
}
return await getres.text();
}).then(finalres=> { console.log("finalres is: " + finalres, null); });
虽然我用过await
,但似乎并没有什么帮助。我希望有人能帮助我。
解决方案
我会使用await
逻辑使代码看起来是同步的。使用 时await
,直到操作完成后才会执行下一行。
const url = "myUrl";
let bodyText = JSON.stringify({ data: dataResult });
const postres = await fetch(url, {
method: "POST",
headers: { 'Content-Type': 'application/json', 'header': 'myHeader'},
body: bodyText
});
if (!postres.ok) {
console.log("error1");
return; // return to stop execution???
}
console.log("success1");
const getres = await fetch(postres.headers.get("something"), {
method: "GET",
headers: { 'header': 'myHeader'}
});
if (!getres.ok) {
console.log("error2");
return; // return to stop execution???
}
console.log("success2");
const finalres = await getres.text();
console.log("finalres is: " + finalres, null);
推荐阅读
- c# - 单击菜单添加项目时如何根据特定模板添加项目?
- spring - 反应式 Spring 安全性:@PreAuthorize Spring-EL Expression with Mono
- laravel - 社交名流注册后的动态用户角色分配
- swift - 无法使用 Core Data 类解码 JSON
- python - 按行值比较数据框列并选择具有匹配模式的列
- clang - 缺少clang尾随参数包的默认参数
- reactjs - 如何在 react-native 中向日历提供可选日期的自定义列表
- r - 将由两个不同分隔符分隔的字符串中的值列表转换为单独的行
- javascript - 如何从 webpack 包中导入?
- .htaccess - Icomoon 字体不会显示在服务器上