当我的代码完成其进程时,终端会继续运行,我需要手动将其关闭。过去,我使用 mongoose.disconnect() ,这似乎将其关闭,但这在这里不起作用,因为当我使用它时(即使使用等待),它会在写入所有 8,000 多条记录之前关闭到我的数据库。
这是代码示例:
const MyFunction = array => {
for (let i = 0; i < array.length; i++) {
const item = new Item({
property1: array[i].property1,
property2: array[i].property2,
});
item.save();
}
};
const Final = async () => {
try {
const array = [{property1, property2}] // 8,000 items long
await SharedFunctions.connectToMongoDb();
await MyFunction(array);
} catch (err) {
console.log(err);
}
};
Final();
最佳答案
关于 Node 进程未退出或终端未退出,可能有多种原因。像打开数据库连接,打开句柄等。 Node 有足够的能力来查看一切是否完成并退出代码。您可以在 await MyFunction();
后手动调用 process.exit
退出,但理想情况下您不需要这样做。
所以我也建议使用 https://github.com/mafintosh/why-is-node-running包以查找任何打开的句柄。您需要将其添加到您希望程序终止的位置。所以在你的情况下它会是这样的
const log = require("why-is-node-running");
onst Final = async () => {
try {
await SharedFunctions.connectToMongoDb();
await MyFunction();
log();
} catch (err) {
console.log(err);
}
};
Final();
编辑:根据您对问题的最新编辑,您需要将 MyFunction 更改为这样
const MyFunction = array => {
return Promise.all(array.map(row => {
const item = new Item({
"property1": row.property1,
"property2": row.property2
});
return item.save();
}));
};
请记住,并行执行如此多的操作可能会导致问题,您也可以尝试此操作
const MyFunction = async array => {
for (const row of array) {
const item = new Item({
"property1": row.property1,
"property2": row.property2
});
await item.save();
}
};
关于javascript - 异步函数完成时如何停止终端运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59737239/