user12640130
user12640130

Reputation:

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

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. Can somebody find out what's my problem?

Current output:

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

Expected output:

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

Upvotes: 0

Views: 43

Answers (1)

dor272
dor272

Reputation: 738

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!");

Upvotes: 2

Related Questions