Reputation: 57
I have declared 2 methods as findSuitableRoom
and getRooms
. The getRooms
function is calling inside the findSuitableRoom
method. I want to wait until the getRooms
function executed. Since I used async/await
. Yet it does not wait.
Implementations :-
async function findSuitableRoom(_lecturer, _sessionDay, _sessionTime, _sessionDuration, _sessionType){
//other implementations
rooms = await getRooms(_sessionType, lecturer.fullName);
console.log("FindSuitableRoom function "+rooms.length)
response = await assignRoom(rooms, _sessionDuration, lecturer.level, lecturer.fullName);
}
async function getRooms(type){
let roomsByType = "";
await Rooms.find({type : type},
async (err, rooms) => {
if (rooms){
roomsByType = rooms;
console.log("Get Room Function "+roomsByType.length)
} else {
console.log('No Rooms')
}
})
return roomsByType;
}
I used console.log() to get the length of responses. It printed in the console as below
Get Room Function 6
FindSuitableRoom function 6
FindSuitableRoom function 0
Get Room Function 5
Get Room Function 6
FindSuitableRoom function 6
Get Room Function 6
FindSuitableRoom function 6
What changes do I need to add in order to make this functionality synchronous?
Upvotes: 0
Views: 134
Reputation: 16472
Usually when you use await
then you should directly collect the result of the function instead of using a callback.
async function getRooms(type) {
let roomsByType = [];
let roomsByType = await Rooms.find({ type: type });
if (roomsByType.length) {
console.log("Get Room Function " + roomsByType.length)
} else {
console.log('No Rooms')
}
return roomsByType;
}
Upvotes: 1