【发布时间】:2018-06-28 12:45:37
【问题描述】:
我正在使用 NodeJs 和 MongoDB 来开发 Web Api。
我遇到了我的 await 语句没有被等待的问题...
这是一个代码示例和输出,对我来说毫无意义..
代码
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");
}
输出
---------------------- EXIT
API: FOUND place
API: FOUND place
---------------------- DONE
预期输出
API: FOUND place
API: FOUND place
---------------------- DONE
---------------------- EXIT
【问题讨论】:
-
你使用的是回调版本的connect,..
-
是的,但这应该是同步的吧?但它的行为是异步的......
-
Yes, but that should be synchronous right?Docs say ->Returns: Promise if no callback passed.. 所以没有.. -
另外,如果您使用 async/await,请使用它。为什么首先使用回调.. 只需执行 ->
const db = await MongoClient.connect(url);并完成它。
标签: javascript node.js mongodb asynchronous