How to deal with async/await hell?

  • A+
Category:Languages

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?

 


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 }) ]); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: