Dmitry Mogilevich Dmitry Mogilevich - 1 year ago 88
Node.js Question

How to return value in collection.find({})

var shortLinks = [];

Link.find({}, function (err, links) {

if (err) {
console.log(err);

} else {

links.map(link => {
shortLinks.push(link.shortLink);
});

}
console.log(shortLinks);//shortLinks has values, all okey
});

console.log(shortLinks); //shortLinks is empty


i need to use shortLinks after Link.find({}) but array is empty.
Need to return shortLinks.

Answer Source

Callbacks. The function(err, links) is called asynchronously, so shortLinks isn't populated until that function is called. Your bottom console.log is being called first, due to how callbacks work.

https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes/Declaring_and_Using_Callbacks

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download