0

I'm impractical with node js. I have the following code:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");

    dbo.collection("test").findOne(
        {},
        { sort: { _id: -1 } },
        (err, data) => {
            console.log(data);
        },
    );
    db.close();
});

I would like to use the variable "data" outside the scope of MongoClient.connect (). The problem should be that a callback function is used and is therefore executed asynchronously.

If I do something like this:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

var x;

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");

    dbo.collection("test").findOne(
        {},
        { sort: { _id: -1 } },
        (err, data) => {
            console.log(data);
            x = data;
        },
    );
    db.close();
});

console.log(x);

The result of x will be "undefined".

How can this problem be solved in general? How do you use variables outside of a certain scope in order to execute the code in a pseudo-synchronous manner?

rfivbiiz
  • 11
  • 2
  • 1
    https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – danronmoon Jul 18 '19 at 19:59
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Davin Tryon Jul 18 '19 at 20:30

1 Answers1

0

you can use async and wait to convert this asynchronous code to synchronous code,

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

var x;

(async ()=>{
 await MongoClient.connect(url, (err, db) => {
    if (err) throw err;
    var dbo = db.db("mydb");

    dbo.collection("test").findOne(
        {},
        { sort: { _id: -1 } },
        (err, data) => {
            console.log(data);
            x = data;
        },
    );
    db.close();
});
})();
console.log(x);

to learn more,

https://tylermcginnis.com/async-javascript-from-callbacks-to-promises-to-async-await/ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function