【问题标题】:How do I return data from a function in Node that connects to Mongodb? [duplicate]如何从连接到 Mongodb 的 Node 中的函数返回数据? [复制]
【发布时间】:2018-06-22 10:51:23
【问题描述】:
function getEmployees(jobID){
    MongoClient.connect(url, function(err, db){
        if(err) throw err;
        var dbo = db.db("mydb");
        dbo.collection("employees").find({employee:jobID}).toArray(function(err, result){
            if(err) throw err;
            db.close();
            console.log(result) // shows the employees. cool!
            // how do I return result??
        })
    })
}
var employees = getEmpoyees(12345);  // I want the employees variable to be an array of employees

我是 node.js 和 javascript 的新手,我想不通。我是否需要实现回调以按照我尝试的方式使用数据?

【问题讨论】:

  • 你能分享你所有的代码吗?你安装并导入mongoose了吗?
  • 您将无法以这种方式获得价值。你以前用过 Promise 吗?
  • “我是否需要实现回调以按照我尝试的方式使用数据?” - 是的,或者最好还是去了解一下 Promises(MongoDB 使用它们开箱即用)。 Promise 与 async / await 配合得特别好。
  • @AlbertoRivera 不,但我现在正在研究它们。

标签: javascript node.js


【解决方案1】:

非常有趣的问题。 在这种情况下,您不能直接返回值。 所以我实现了间接的方式来获取返回值。 为此,我在“getEmployees”函数中添加了“回调”函数作为函数参数。 更新后的代码如下。

function getEmployees(jobID, callBack){
MongoClient.connect(url, function(err, db){
    if(err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("employees").find({employee:jobID}).toArray(function(err, result){
        if(err) throw err;
        db.close();
        console.log(result) // shows the employees. cool!
        // you can return result using callback parameter
        return callBack(result);
    })
})
}
var employees = getEmpoyees(12345, function(result) {
   console.log(result);
});  // I want the employees variable to be an array of employees

【讨论】:

  • “非常有趣的问题” - 我认为您将“有趣”与“常见”混淆了。
  • 这成功了!谢谢。
  • 实际上,console.log(result) 输出了结果,但employees 变量仍未定义:(
  • 结果未定义的唯一情况是函数在“返回”查询之前完成。所以我认为数据库错误发生在callBack之前。
  • 结果未定义的唯一情况是函数在'return'查询之前完成。我认为发生了数据库错误,所以 callBack 没有运行。如果我的回答是正确的,你会投票吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多