【问题标题】:How to use await in post/get requests using fetch?如何在使用 fetch 的 post/get 请求中使用 await?
【发布时间】: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


【解决方案1】:

我会使用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);

【讨论】:

  • 非常感谢您的回答。我首先有这个逻辑,但它没有帮助。当我运行这样的代码时,我在最后一个 console.log() 上得到“尚未开始”的结果,原因是,正如我所说,完成该过程大约需要 5-8 秒。开始状态为“未启动”,然后变为“处理中”,最后变为“成功”。但是使用这段代码,我总是得到“未开始”的答案。
  • @user1419243 您能否分享一个负责“已启动”/“未启动”的代码示例?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 2017-06-02
  • 2021-03-16
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多