0

Im confused why hold is returning nothing -> [] in this function.

Ideally I need to run this request a few times, each response should be added to the array. Why are my values not being added to this list?

const gather = async (round) => {
    console.log("RUNNING");
    const hold = [];
    [...Array(round).keys()].forEach(async (x) => {
      const minLat = -90;
      const minLon = x;
      const maxLat = 90;
      const maxLon = x + 5;
      const params = `minLat=${minLat}&minLon=${minLon}&maxLat=${maxLat}&maxLon=${maxLon}`;
      const url = `URLHERE`;
      const response = await fetch(url);
      const body = await response.text();
      const results = body.split("<raw_text>");
      hold.push(results);
    });
    console.log(hold);
  };
Nick H
  • 205
  • 2
  • 9
  • 1
    This happens because `forEach` is not async (and making the callback async won't make it async). For your scenario, you should use a plain `for` loop which will correctly handle the `await` you have inside the callback. Otherwise, you must map the whole array to a Promise map and resolve all the promises before logging `hold` – briosheje Feb 15 '22 at 16:26
  • Perhaps this example might help you understand (and play around): https://jsfiddle.net/c09qtp14/ . Also, check the duplicate link provided by VLAZ. – briosheje Feb 15 '22 at 16:32

0 Answers0