for-loop 和 await fetch

for-loop together with await fetch

我正在执行下面的代码,问题是 URLS 一下子全是 运行。我希望在第一个 URL 完全加载后,一个一个地加载 url。我该怎么办?我试图将获取更改为等待获取,但我收到错误:"await is only valid in async functions and async generators"

非常感谢。

  for (let j = 0; j < 5; j++) {
    fetch("http://www.example.com/post.php", {
      "credentials": "include",
      "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Requested-With": "XMLHttpRequest"
      },
      "referrer": "http://www.example.com/index.php",
      "body": "id=",
      "method": "POST",
      "mode": "cors"
    });
  }

您可以使用 async/await

创建一个 async 函数,这样您就可以在其中 await

let fetchExmaple = async function () {
 for (let j = 0; j < 5; j++) {
    await fetch("http://www.example.com/post.php", {
      "credentials": "include",
      "headers": {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
        "Accept": "*/*",
        "Accept-Language": "en-US,en;q=0.5",
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Requested-With": "XMLHttpRequest"
      },
      "referrer": "http://www.example.com/index.php",
      "body": "id=",
      "method": "POST",
      "mode": "cors"
    })
  }
}

请查看 here 以了解它如何与 async/await 一起使用以及 Promise 的示例(使用 Timeout 用于演示目的 - 在您的情况下,它是一个 fetch 函数,其中 returns 一个 Promise)。