0

I got a problem that the await Promise.all is not working in my case. I attached the code and the output I got:

    await Promise.all(allIndizes.map(async (index) => {
        await axios.get(uri)
            .then(async function (response) {
                let searchResult = response.data.hits.hits;
                console.log('Search Result: ' + searchResult);
                await Promise.all(searchResult.map(async (element) => {
                    await primaryKeyModel.findById(element._id).exec((err, pk) => {
                        console.log('PK, direct after search: ' + pk);
                      //DO SOME STUFF HERE BUT DELETED IT TO SHORTEN THE CODE
                        }
                    })
                    console.log('test1');
                }));
            })
        console.log('test2');
    }));

The output is the following:

test1
test2
PK, direct after search: { _id: 5bf1c0619674e2052a4f6a64 ... }

I actually would actually expect that the first output is the 'PK, direct after search'. I don't understand why the function is not waiting? Do someone has a hint, whats wrong here? I found a similar issue here and I adopted the logic but its still not working. Thanks for the help. I tried to shorten the code as much as possible. I only deleted statements which are not affecting the async execution.

Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
Max
  • 3
  • 1

1 Answers1

0

Mongoose supports promises for a long time, callback-based API is obsolete, it's a mistake to use it where a promise is expected (await).

then is unwanted inside of async functions, this defies the purpose of using async..await.

It should be:

await Promise.all(allIndizes.map(async (index) => {
    const response = await axios.get(uri);
    let searchResult = response.data.hits.hits;

    await Promise.all(searchResult.map(async (element) => {
        const pk = await primaryKeyModel.findById(element._id);
        //DO SOME STUFF HERE BUT DELETED IT TO SHORTEN THE CODE
    }));
}));
Estus Flask
  • 206,104
  • 70
  • 425
  • 565