我正在尝试从mongodb获取大数据
有我的代码
let cont = 0
const stream = await dataModel.find({}).lean().cursor(); // it will return around 2.000 elements
console.log("Checkpoint one")
await stream.on('data', async (res) => {
try {
cont += 1
} catch (e) {
console.log(e)
}
});
await stream.on('close', () => {
console.log(`Execution ended. Number of elements: ${cont}.`);
});
console.log("Checkpoint two")
输出:
Checkpoint one
Checkpoint two
Execution ended. Number of elements: 2194.
预期输出:
Checkpoint one
Execution ended. Number of elements: 2194.
Checkpoint two
当我尝试在“ on data”功能中控制台记录每个资源时,它也在“ Checkpoint two”之后控制台记录日志,
答案 0 :(得分:1)
javascript
stream.on('close', () => {
console.log(`Execution ended. Number of elements: ${cont}.`);
});
定义(而不是“执行”)一个函数(每次关闭流时都会调用),然后直接执行代码执行。您不能await
,也不能await
stream.on('data')
,因为这是相同的问题。
如果希望父函数等待流完成读取的位置,则可以创建new Promise
函数填充的stream.on('close')
。然后,您可以await
之前console.log("Checkpoint two")
进行承诺。这应该可行,您也许想尝试一下。