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