首页 > 解决方案 > 如何在使用 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,但似乎并没有什么帮助。我希望有人能帮助我。

标签: node.jstypescriptpostasync-awaitfetch

解决方案


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

推荐阅读