0

CategoryModel.find, gathers all records inside a db. Error if something goes wrong and categories is my output array.

categoryModel.find(function(error, categories) {
  if(error){
    console.log(error)
  }
});

I need to reach that categories outside of the function.

var result = categoryModel.find(function(error, categories) {
  if(error){
    console.log(error)
  }
  console.log(categories)
});

console.log(result.categories)

This type is not working. Im beginner at javascript :( Thanks

SOLVED

var result = {}
categoryModel.find(function(err, categories) {
  console.log(categories)
  result = categories
  callback(result)
});

console.log(result)
Community
  • 1
  • 1
Berkin
  • 1,565
  • 5
  • 22
  • 48

1 Answers1

0

Like @briosheje said in the comment, you should use async / await.

For your case, it would look like this:

async function someFunction() {
  var result = await categoryModel.find();
  if (result.error) {
    console.log(error);
  }
  console.log(result.categories);
}

You can read more about async / await there.

julien
  • 86
  • 2
  • 8