【问题标题】:Waiting for async "findOne" to finish before returning value在返回值之前等待异步“findOne”完成
【发布时间】:2019-04-08 01:38:51
【问题描述】:

我有一个名为 extrafunctions.js 的文件,它导出要由 app.js 运行的函数。其中一个函数包括 MongoDB 查询 findOne。问题是该函数在查询完成之前返回一个值,因此 app.js 没有获得所需的数据,而是“未定义”。

我已经在一定程度上尝试过 Promise,但没有任何效果。

app.js:

const extraFunctions = require("./extraFunctions");
app.get('/api/login', (req, res) => {
    res.end(extraFunctions.login());
});

extraFunctions.js:

function login () 
{
client.connect(err => {
    var collection = client.db("site").collection("test");
    collection.findOne({}, (err, result) => {
        if (err) throw err;
        console.log(result);
        return result;

    });
    client.close();
}); 
}

module.exports.login = login;

固定版本 与接受的评论相同,但必须将 res(result) 更改为 res(JSON.stringify(result))

【问题讨论】:

标签: javascript node.js mongodb asynchronous


【解决方案1】:

你需要使用promise或者async-await,下面是一个promise实现的例子:

应用js

const extraFunctions = require("./extraFunctions");
app.get('/api/login', (req, res) => {
    extraFunctions.login().then(result =>{
        res.end(result);
    })
});

extraFunctions.js

function login() {
    return new Promise((res, rej) => {
        client.connect(err => {
            if(err){
                rej(err)
            }
            var collection = client.db("site").collection("test");
            collection.findOne({}, (err, result) => {
                if (err) rej(err);
                console.log(result);
                res(result)
            });
            client.close();
        });
    })
}

module.exports.login = login;

【讨论】:

    【解决方案2】:

    如果您使用本机 mongodb 连接器,则它提供 Promise 支持。你可以像这样使用:

    // connection is a promise
    const connection = MongoClient.connect(url, { useNewUrlParser: true });
    
    // async function
    async function login () {
      let result;
      try {
        const client = await connection;
        var collection = client.db("site").collection("test");
        try {
          result = await collection.findOne({})
        } catch (err) {
          throw err;
        }
        client.close();
      } catch (e) {
        throw e;
      }
      return result;
    }
    
    module.exports.login = login;
    

    在您的路线中:

    const extraFunctions = require("./extraFunctions");
    app.get('/api/login', async (req, res, next) => {
      try {
        const result = await extraFunctions.login();
        res.end(result);
      } catch (e) {
        next(e);
      }
    });
    

    【讨论】:

    • const result = await extraFunctions.login();获取错误“等待只是一个有效的异步函数”
    • 你把async放在(req, res, next)回调之前了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多