当我的代码完成其处理后,终端将继续运行,而我需要手动将其关闭。过去,我使用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();
答案 0 :(得分:3)
关于节点进程未退出或终端未退出,可能有多种原因。像开放式数据库连接,开放式句柄等。节点具有足够的功能,可以查看是否一切完成并退出代码。您可以在process.exit
之后手动调用await MyFunction();
退出,但理想情况下您不需要这样做。
所以我也建议使用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();
}
};