node.js - JavaScript out of scope undefined -


var http = require('http'); var mongoclient = require('mongodb').mongoclient; var url = "mongodb://localhost:27017/testdb";  var companies = [{'name' : 'sun pharma', 'medicine' : [1, 2]},                 {'name' : 'hello pharma', 'medicine' : [3, 4]},                 {'name' : 'sayan pharma ltd.', 'medicine' : [5]}]  mongoclient.connect(url, function(err, db) {   if (err) throw err;   var companycollection = db.collection ('company');   companies.foreach ((company) => {     companycollection.insert (company);   });   var out;   companycollection.find({}).toarray(function (err, result) {     if (err) {       console.log (err);     } else if (result.length) {       console.log (result); // prints correct array       out = result;       console.log (out); // prints correct array     } else {       console.log ('no documents found');     }     db.close();   });   console.log (out); // prints undefined }); 

the variable out assigned equal result. when result , out printed within function scope, prints correctly, when print out outside function, it's undefined. why happening , how fix it?

  var out = [];  // 1.   companycollection.find({}).toarray(function (err, result) {     if (err) {       console.log (err);     } else if (result.length) {       console.log (result); // 3. asynchronous code in callback       out = result;       console.log (out); // 4. asynchronous code in callback     } else {       console.log ('no documents found');     }     db.close();   });   console.log (out); // 2. synchronious code 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -