0

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.

1 Answers1

2

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!");
dor272
  • 550
  • 1
  • 6
  • 26
  • "You can't use await and callbacks at the same time." you literally nailed it. Now I realize why understanding promises, async & await has been so ridiculously "hard". –  May 16 '20 at 21:58
  • @FooBar3098 Actually, there's no hard rule that says that it's not possible to use callbacks and promises (async/await) together. It's just that the API designer for the `findOne()` function didn't think of it. He probably thought: "Oh, you're passing me a callback? You probably don't want a promise then". Though to be fair I'd never allow both myself. It would be confusing. Which do I execute? The callback? The promise's `.then()` callback? Both? If both then which do I execute first etc. – slebetman May 16 '20 at 22:30
  • True. Good example: Axios works nicely with `.then` but MongoDB methods don't. Not sure which ones or all but at least findOne `.then` is an undefined method. –  May 16 '20 at 22:59