简体   繁体   中英

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.

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.

Lucky for us that now is 2018, the syntax of running synchronous function is super easy with async/await. In this case getProducts should be run synchronously and should be like this:

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:

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 . So that, getProducts have to return a Promise .

Here try this code in 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

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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