首页 > 解决方案 > Why does my function comprised of asynchronous functions not returning correct value? (NodeJS)

问题描述

A variable which is assigned within async functions is not returning the expected output.

I am currently writing a NodeJS function that finds an object from a MongoDB database (the database works perfectly) and returns an object if it is found. The problem is that the functions' comprising async functions don't wait until the previous functions are finished. I am relatively new to JS and NodeJS, so it may be that I am misunderstanding how the async functions act.

async function findUserByEmail (userEmail) {
    var mg = require('mongodb').MongoClient;

    var user;

    await mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, async function(err, db){
        var dbo = db.db(myDB);
        var query = { email : userEmail };

        await dbo.collection("Users").findOne(query).then((result)=>{
            user = result;
            db.close();
        });
    });

    return user;
}

I am trying to return the value assigned to "user" within the "findOne(query)" function, however, the value returned is always "undefined".

标签: node.jsasync-await

解决方案


您正在混合回调和异步调用。所以让我把它清理干净。瞧,这里你做了一些应该工作的东西(你有一些我不知道的值,例如 myDB 和 url)。

async function findUserByEmail (userEmail) {
    var mg = require('mongodb').MongoClient;
    var db = await mg.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
    var result;

    // Add a Try/Catch to capture any errors, 
    // such that the database can still be closed
    try {  
        var dbo = db.db(myDB);
        var query = { email : userEmail };
        result = await dbo.collection("Users").findOne(query);
    } catch (error) {
        throw error;   
    } finally {
        db.close();
    }
    return result;
}

注意:我建议在应用程序启动时打开一次 MongoDB 连接,在它因任何原因关闭时重新打开它,并在应用程序停止时关闭它,因为为每个请求打开一个新连接会增加一些显着的开销(想想可能会慢 25 倍)。


推荐阅读