简体   繁体   English

Node.js 中的异步循环

[英]Asynchronous Loops in Node.js

 async function bald(fileName) { try { let aPayload = ''; let aStream = fs.createReadStream(`./tmp/${fileName}`, 'utf8'); aStream.on('data', (chunk) => { aPayload += chunk; }).on('end', async () => { let aJson = JSON.parse(aPayload); for await (let a of aJson) { console.log(a.id); console.log("Tick"); await dbItems.findOne({id: a.id}, (err, result) => { console.log("Something Should Happen;"); }); } }); } catch (e) { throw e; } }

In this answer is content I wanted to try: https://stackoverflow.com/a/50874507/12640130在这个答案中是我想尝试的内容: https://stackoverflow.com/a/50874507/12640130

I found out that forEach won't work at all so I changed it to for... of, but it doesn't make a difference for me.我发现 forEach 根本不起作用,所以我将其更改为 for... of,但这对我没有任何影响。 Can somebody find out what's my problem?有人可以找出我的问题吗?

Current output:当前 output:

ID
Tick
ID
Tick
ID
Tick
// ... and so on.
Something Should Happen!
Something Should Happen!
Something Should Happen!
// ... and so on.

Expected output:预期 output:

ID
Tick
Something Should Happen!
ID
Tick
Something Should Happen!
ID
Tick
Something Should Happen!
// ... and so on.

You can't use await and callbacks at the same time.您不能同时使用等待和回调。 it should be one of the following:它应该是以下之一:

  1. this will not wait for result before iterating.这不会在迭代之前等待结果。
                    dbItems.findOne({id: a.id}, (err, result) => {
                        console.log("Something Should Happen!");
                    });
  1. supposed to be what you're looking for.应该是你要找的东西。
                    const result = await dbItems.findOne({id: a.id})
                    console.log("Something Should Happen!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM