【发布时间】:2021-01-05 18:04:00
【问题描述】:
我有以下代码,但我不喜欢使用
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,为什么还要使用then?你的代码有点难以理解。后续的 http 调用是否依赖于之前的调用? -
我第一次尝试不等待但它根本不起作用,即使没有向我显示任何错误消息。是的,第二次调用取决于第一次调用的自定义标头。
标签: node.js typescript post async-await fetch