Search code examples
javascriptfor-loopfetch-apiconsole.log

for-loop together with await fetch


I am executing the code below, and the problem is, the URLS are all running at once. I want the urls to be loaded one by one, after the first URL has been fully loaded. what I suppose to do? I was trying to change the fetch to await fetch, but I recevie the error: "await is only valid in async functions and async generators"

Thank a lot.

  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"
    });
  }

Solution

  • You could make use of async/await.

    Create an async function so you can await inside of it.

    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"
        })
      }
    }
    

    Please have a look here in order to see how it works with async/await and example of a Promise (used Timeout for demonstration purposes - in your case, it is a fetch function which returns a Promise).