简体   繁体   English

嵌套的javascript函数返回身份不明

[英]Nested javascript function returning unidentified

I am having trouble returning some database values to my server in nodejs, it seems that on the way the values are lost.我在 nodejs 中将一些数据库值返回到我的服务器时遇到问题,似乎在途中这些值丢失了。

result is loged fine and i am findining my data, but it is lost in the return.结果记录良好,我正在查找我的数据,但它在返回时丢失了。

exports.getProducts = async function () {

return await MongoClient.connect(url, {useNewUrlParser: true}, async function 
(err, client) {
let db = client.db(dbName);
return await db.collection('products').find({}).toArray(async function (err, 
result) {
  if (err) throw err;
  client.close();
  console.log(result);
  return await result
});
});
}

you should learn about asynchronous , callback and promise in javascript, after that you can work with javascript easily, and my code below can be understandable to you.你应该学习javascript中的asynchronouscallbackpromise ,之后你就可以轻松地使用javascript了,我下面的代码对你来说是可以理解的。

Lucky for us that now is 2018, the syntax of running synchronous function is super easy with async/await.幸运的是,现在是 2018 年,使用 async/await 运行synchronous function的语法非常简单。 In this case getProducts should be run synchronously and should be like this:在这种情况下getProducts应该synchronously运行,并且应该是这样的:

app.get('/api/products/', async function(req, res, next) {
    const myData = await mongo.getProducts();
    res.send(myData);
});

edit: mongodb.js should be update a little bit:编辑: mongodb.js应该更新一点:

exports.getProducts = function() {
   return mongoClient.connect(url, {useNewUrlParser: true }, function(err, client) { 
      let db = client.db(dbName);

      return db.collection('products').find({}).toArray( function(err, result) { . 
          if(err) throw err;
          client.close();
          return result;
   }
   })
}

Q: what's the difference?问:有什么区别? A: await is waiting for a Promise be resolved with value . A: await正在等待一个Promise被解析为value So that, getProducts have to return a Promise .因此, getProducts必须return一个Promise

Here try this code in mongodb.js在 mongodb.js 中试试这个代码

 const MongoClient=require('mongodb').MongoClient const assert=require('assert') const url='mongodb://localhost:27017'; const dbName="productstoredb" var Result; var MongoDB; var MongoConnect = new Promise((resolve, reject) => { var Db = MongoClient.connect(url, { useNewUrlParser: true }, function (err, client) { if (err) { resolve("error") } MongoDB = client.db("dbName") MongoDb.db(dbName) resolve("connected to the Database") }) }) var MongoView = new Promise((resolve, reject) => { MongoDB.collection("products").find().toArray(function (err, result) { if (err) resolve("ERROR"); Result = result; resolve("success") }) }) exports.getProducts = async function () { console.log(await MongoConnect); console.log(await MongoView); return Result; }

and also add await on your api并在您的 api 上添加await

 app.get('/api/products', function (req, res) { var mydata = await mongo.getProducts(); res.send(Mydata) })

you should google Promise , async - await .The connection to your mongodb doesnt happen instantaneously.Your code makes the call to connect to your database then It starts executing the next line of code even before that connection is established.你应该谷歌Promiseasync - await 。到你的 mongodb 的连接不会立即发生。你的代码调用连接到你的数据库,然后它甚至在建立连接之前就开始执行下一行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM