【问题标题】:await doesn't seem to wait till the async call is finishedawait 似乎没有等到异步调用完成
【发布时间】:2016-01-31 19:02:15
【问题描述】:

我有一个使用await 调用的异步函数,我认为当你使用await 时,它应该暂停函数执行,直到它收到它的值。出于某种原因,它对我不起作用。

这是我的函数(它在一个类中):

async userExistsInDB(email) {
    let userExists;
    await MongoClient.connect('mongodb://127.0.0.1:27017/notificator', async(err, db) => {
        if (err) throw err;

        let collection = db.collection('users');
        userExists = await collection.find({email: email}).limit(1).count() > 0;
        console.log("INSIDE:\n", userExists);
        db.close();
    });
    console.log("OUTSIDE:\n", userExists);
    return userExists;
}

这是我在同一个类中的另一个函数中调用它的方式:

async getValidationErrors(formData) {
   let userExists = await this.userExistsInDB(formData.email);
   console.log("ANOTHER FUNC:\n", userExists);
}

所以,我得到以下输出:

OUTSIDE:
 undefined
ANOTHER FUNC:
 undefined
INSIDE:
 true

虽然值 INSIDE: true 我希望第一个打印出来。

基本上,我需要的是从userExistsInDB 函数中获取布尔值userExists 并在其他代码中使用它。

我在这里做错了什么?

【问题讨论】:

    标签: ecmascript-6 async-await ecmascript-2017


    【解决方案1】:

    await 仅适用于 Promise,因此 MongoClient.connect(…) 需要返回一个 Promise。然而,您将它用作回调 API,甚至使用 async(承诺返回)回调函数,这不起作用。假设如果你不传递回调,mongo 返回承诺,你的代码应该看起来像

    async function userExistsInDB(email) {
        let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
        let collection = db.collection('users');
        let userExists = (await collection.find({email: email}).limit(1).count()) > 0;
        db.close();
        return userExists;
    }
    

    虽然理想情况下你宁愿这样做

    async function userExistsInDB(email) {
        let db = await MongoClient.connect('mongodb://127.0.0.1:27017/notificator');
        try {
            let collection = db.collection('users');
            let userCount = (await collection.find({email: email}).limit(1).count();
            return userCount > 0;
        } finally {
            db.close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-21
      • 2019-06-03
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2021-01-30
      相关资源
      最近更新 更多