Reputation: 9407
I have the following...
let user;
let room;
await (async () => {
user = User.findOne({ room_id: data.room_id });
room = Room.findOne({ room_id: data.room_id });
})();
await console.log(user, room);
I have multiple database queries and I want them to be asynchronous and at the same time, I want the results to be saved into variables. I tried the code above, but once the console.log
gets reached, neither query has been executed yet. The only way I can make it work is if I change it to the following...
let user = await User.findOne({ room_id: data.room_id });
let room = await Room.findOne({ room_id: data.room_id });
await console.log(user, room);
Is there no way to make the queries perform asynchronously but finish executing before console.log()
gets reached?
Upvotes: 1
Views: 1632
Reputation: 198294
Use Promise.all
to wait for multiple parallel promises to finish:
let [user, room] = await Promise.all([
User.findOne({ room_id: data.room_id }),
Room.findOne({ room_id: data.room_id })
]);
Upvotes: 16