0

I'm a beginner in nodejs and javascript in general. I want to access a collection and then store my query that I retrieve into an array so later I can do more stuff with that array. However, when I store the results in the array it doesnt outside the function. Here's my code

const http = require('http');
const bodyParser = require('body-parser');
const locations = require('./models/vicitmsLocation');
const async = require('async');


var postcode = [];

locations.getAllTheIncidents({},function (err, results) {
if (err) {
    throw err;
} else {

    postcode.push(results);
    //Here the code works and array will be populated with data I want
    console.log(postcode);
} 
});
//Here it doesnt work and array is empty.
console.log(postcode);

I understand that this might be an issue with async nature of nodejs and mongo but I cant seem to figure out why this is happening.

M.Asgari
  • 31
  • 3
  • 9
  • refer my answer from https://stackoverflow.com/questions/48785020/why-variable-is-undefined-in-nodejs-express/48785124#48785124 – Rahul Sharma Feb 14 '18 at 17:27
  • I dont quite understand hows that gonna help in my case! – M.Asgari Feb 14 '18 at 17:31
  • because of async nature, the last console executes before getAllTheIncidents callback returns data. So if your next code is dependent on the result of callback then you have to write inside the callback function. – Rahul Sharma Feb 14 '18 at 17:35

1 Answers1

0

Its because nodejs is nonblocking, So, the console.log outside is being executed before the callback of locations.getAllTheIncidents is executed.

So, you have to either use postcode inside the callback or bind locations.getAllTheIncidents inside a promise

Akash Dathan
  • 4,348
  • 2
  • 24
  • 45