[英]Why does my exit process execute before the loop ends?
I came from Ruby, so I spent a day to figure out why process.exit(1) executes before loop end. 我来自Ruby,所以花了一天的时间弄清楚为什么process.exit(1)在循环结束之前执行。 Any ideas what I need to change to make it work?
有什么需要改变的想法才能使它起作用吗?
export default async () => {
const workbook = Xlsx.readFile(path.join(__dirname, './excel.xlsx'));
const data = Xlsx.utils.sheet_to_json(workbook.Sheets.Extract, {
header: getHeaderFor(workbook.Sheets.Extract),
});
await data.map(async (product, index) => {
if (index < 6) return;
await processProduct(product);
});
process.exit(1);
};
I think that If you replace: 我认为,如果您更换:
await data.map(async (product, index) => {
if (index < 6) return;
await processProduct(product);
});
with 与
for (let i = 6; i < data.length; i++) {
await processProduct(data[i]);
}
your problem will be solved. 您的问题将得到解决。
Some explanation: javascript's map function is creating new array from source array when it is calling a callback function for each element of the source array and pushing the returned value of the callback into the result array. 一些解释: javascript的map函数在为源数组的每个元素调用回调函数并将回调的返回值推入结果数组时,从源数组创建新数组。 In this case
await data.map(...
is invalid statement, because the result of map
is array. To fix this it is possible to wrap the result in await Promise.all(data.map(...))
or to use a normal for
loop. You can use the first case when you don't care about concurrency and the second case when you want to achieve sequential order. 在这种情况下,
await data.map(...
是无效的语句,因为map
的结果是数组。要解决此问题,可以将结果包装在await Promise.all(data.map(...))
或使用普通的for
循环,当您不关心并发时,可以使用第一种情况,而当您要获得顺序顺序时,可以使用第二种情况。
While @codtex's answer will work, it will also result in poor performance since each iteration of the loop will wait until the previous iteration. 尽管@codtex的答案有效,但由于循环的每次迭代都将等到之前的迭代,因此也会导致性能下降。 What you really want to do is collect all of the Promises, and then wait for them to finish:
您真正想做的是收集所有的Promise,然后等待它们完成:
const promises = data.map((product, index) => {
if (index < 6) return;
return processProduct(product);
});
await Promise.all(promises);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.