1

呼び出しを使用する非同期関数があり、を使用すると、受け取った値まで関数の実行を一時停止する必要が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最初に印刷されると予想される値ですが。

基本的にuserExists、関数からブール値を取得し、userExistsInDBそれを他のコードで使用する必要があります。

ここで何が間違っていますか?

4

1 に答える 1

5

awaitpromiseでのみ機能するためMongoClient.connect(…)、promise を返す必要があります。それでも、それをコールバック API として使用していて、async(promise を返す) コールバック関数を使用しても機能しません。コールバックを渡さない場合、mongo が promise を返すと仮定すると、コードは次のようになります。

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();
    }
}
于 2015-10-31T13:49:47.820 に答える