Reputation: 2913
I'm using NodeJs and MongoDB to dev a Web Api.
I encounter the problem that my await statements are not being awaited...
Here is a code example and the output, it makes no sense to me..
Code
async find_nearby_places(lng, lat, tag, maxDistance) {
let results = [];
await MongoClient.connect(url, async function (err, db) {
let places= db.db(db_name).collection(collection_places);
let nearbyplaces = places.find({
"location":
{
$near:
{
$geometry: {
coordinates: [lng, lat]
},
$maxDistance: maxDistance
}
},
"tags": {
$in: [tag]
}
});
await nearbyplaces.toArray().then(
async placeArray => {
placeArray.forEach(place => {
console.log("API: FOUND place");
results.push(placeModel.ToplaceModel(place))
});
await db.close();
});
console.log(' ---------------------- DONE')
});
console.log(" ---------------------- EXIT");
}
Output
---------------------- EXIT
API: FOUND place
API: FOUND place
---------------------- DONE
Expected output
API: FOUND place
API: FOUND place
---------------------- DONE
---------------------- EXIT
Upvotes: 2
Views: 309
Reputation: 4553
Await only waits if a promise is returned, for functions with callbacks, new promise has to be defined.
async find_nearby_places() {
await new Promise((resolve, reject) => {
MongoClient.connect(url, async function (err, db) {
//Do tasks
Promise.resolve()
}
})
}
The resolution can be done with any value, in which case the promise will give back that returned value.
Upvotes: 1
Reputation: 749
Your function find_nearby_places
is an async
function .
.
then your other actions except console.log(" ---------------------- EXIT");
are on await
mode..
Soo this line console.log(" ---------------------- EXIT");
never wait for to execute. but other actions
are in await
mode.so they are to be executed one by one
as long as to be waited
Upvotes: 0