My code looks something like this:
(async () => {
try {
const results = await heavyCalculation();
saveResultsToFiles(results);
} catch (e) {
handleError(e);
} finally {
process.exit(0);
}
})();
const saveResultsToFiles = (results) => {
results.forEach(result => {
(async () => await saveResultFile(result));
})
}
const saveResultFile = (result) => {
return promiseToPreprocess(result)
.then(processedResult => saveToFile(processedResult))
}
const promiseToPreprocess = async (result) => {
// this function returns a promise to preprocess the data
}
const saveToFile = (data) => {
// this function synchronously saves data to a file
}
I thought this code would
- perform calculations
- wait for each piece of the results to be preprocessed and saved to a file
- then exit
The first step works, as the program seems to await the heavy calculation results. However, it appears the finally clause is entered before the promise within the forEach-loop is resolved, causing the program to exit early. What am I doing wrong?