0
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.

  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Soren May 30 '16 at 23:28
  • Before completion of your query Results your outside shortlinks gets printed as NodeJs is asynchronous it does not wait for query to complete. So you are getting empty result. – Shantanu Madane May 31 '16 at 10:41

2 Answers2

0

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

Russbear
  • 1,261
  • 1
  • 11
  • 22
0

need to use promise:

const shortLinks = [];

const getShortLinks = Link.find({}, function (err, links) {

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

    } else {

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

    }
});

getShortLinks.then(function(links){
    console.log(shortLinks);
}, function(err){
    console.log(err);
});
  • You do not NEED to use `promise`. It is a solution to the problem and an abstraction of the callback structure. If you don't understand callbacks then you're going to have a bad time. – Russbear May 31 '16 at 19:02