【问题标题】:NodeJs + Mongo db unable to wait resultNodeJs + Mongo db 无法等待结果
【发布时间】: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


【解决方案1】:

Await 仅在返回 Promise 时等待,对于带有回调的函数,必须定义新的 Promise。

async find_nearby_places() {

  await new Promise((resolve, reject) => {
    MongoClient.connect(url, async function (err, db) {
       //Do tasks
       Promise.resolve()
    }
  })
}

可以使用任何值进行解析,在这种情况下,promise 将返回该返回值。

【讨论】:

    【解决方案2】:

    您的函数 find_nearby_places 是一个 async 函数。 . 那么除了console.log(" ---------------------- EXIT"); 之外,您的其他操作都处于await 模式..

    Soo 这行console.log(" ---------------------- EXIT"); 永远不会等待执行。但其他actions 处于await 模式。所以只要等待它们就会被执行one by one

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 2020-09-23
      • 2015-10-24
      • 2019-04-19
      • 1970-01-01
      • 2017-06-20
      • 2020-06-07
      • 2016-05-28
      • 2021-09-14
      相关资源
      最近更新 更多