0

I have a schema which saves Cat information. I then want to create an array of all the cat_urls, however when I call the array outside of the dbs call, the array is empty

var cat_urls = [];

Cat.find(function (err, data) {
    var stringify = JSON.stringify(data)
    content = JSON.parse(stringify);
    content.forEach(function (result) {
        cat_urls.push(result.cat_url);
    })
    console.log(cat_urls, 'here')
})

console.log(cat_urls, 'here not working') // I want cat_urls to also be populated here

So Inside the Cat.find() call cat_urls has values like this:

[ 'www.hello.co.uk', 'www.testing.co.uk' ] 'here'

But outside cat_urls = []

I guess this is to do with the fact that node js does not run in a specific order, but how can I solve this issue?

1 Answers1

1

I think it's working but your find function returns a promise that resolves asynchronously.

Try:

var cat_urls = [];

Cat.find(function (err, data) {
    var stringify = JSON.stringify(data)
    content = JSON.parse(stringify);
    content.forEach(function (result) {
        cat_urls.push(result.cat_url);
    })
    console.log(cat_urls, 'here')
}).then(function(){
  // Promise has completed, now this console log will trigger only after the cat's names are pushed.
  console.log(cat_urls);
})
Mike
  • 3,830
  • 2
  • 16
  • 23
  • But the aim is to be able to call this outside of that function - with the array being populated rather than empty –  Aug 17 '16 at 18:14
  • @emisqwe Unfortunately the nature of promises are such that they must be resolved before you can guarantee global variables are set. If you have certain oeprations that must be performed, you can enclose them in the function within the `.then(function() {})` statement or even call other functions within that statement. Here's an article that may help you familiarize yourself with promises and how they work in Mongoose http://mongoosejs.com/docs/promises.html. – Mike Aug 17 '16 at 18:25