-2

I have an async function that processes an Array and call another async function by increasing time interval by each element.

I wait for all promises to resolve and then I save the resulting Array in a file. Though for some reasons the write file operation executes before the Promises are resolved. Can somebody tell me what I might be doing wrong?

The read and write file functions are turned into promise with node util and the getGuidesList returns a promise.

(async () => {

  try {
    const file = await readFilePromise('./kommuner.json');
    const municipalities = JSON.parse(file).municipalities;
    console.log(municipalities);
    const municipalities_new = await Promise.all(municipalities.map(async (municipality, index) => {
      setTimeout(async () => {
        let guides = await getGuidesList(municipality.municipality_id);
        // const guides = [];
        if (typeof guides === 'string') {
          guides = [];
        }
        console.log(`Number of guides for ${municipality.municipality_name}: ${guides.length}`);
        Reflect.set(municipality, 'guides_number', guides.length);
        Reflect.set(municipality, 'guides', guides);
        console.log(municipality)
      }, index * 5000);
    }))
    console.log(municipalities_new);
    await writeFilePromise('./kommuner_guide.json', JSON.stringify({
      "municipalities": municipalities_new
    }));
  } catch (err) {
    console.log(err);
  }
})();
Whiat
  • 31
  • 5
  • 2
    I've seen this code before, like an hour ago ... it was closed with a link to a useful answer ...the issue is, there's no way to wait for a setTimeout, so the code inside setTimeout is not waited for – Jaromanda X Mar 08 '20 at 11:12
  • 2
    The `await` inside `setTimeout(async () => {})` is **not** part of the promise chain outside – jonrsharpe Mar 08 '20 at 11:13
  • Thanks. I got my issue solved with the answer below. – Whiat Mar 08 '20 at 21:34

1 Answers1

0

The problem here is this line:

 setTimeout(async () => {

you do a setTimeout call. That will schedule the callback to be called later. But you don't wait for that callback to happen. Instead use some promisified version of setTimeout:

  const timer = ms => new Promise(res => setTimeout(res, ms));

then you can

  await timer(2000);
  await /*other stuff*/;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151