我的代码看起来像这样:
(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
}
我以为这段代码会
执行计算
等待每条结果被预处理并保存到文件中
然后退出
第一步有效,因为程序似乎在等待繁重的计算结果。但是,似乎 finally 子句是在 forEach 循环中的承诺解决之前输入的,导致程序提前退出。我究竟做错了什么?
幕布斯6054654
慕虎7371278
相关分类