0

How can I return the value from nested query? I want to save result to global variable. Somebody can help me?

let result = null;

const returnMeal = () => {
  Dinner1300.count().exec(function (err, count) {

    const random = Math.floor(Math.random() * count)
  
    Dinner1300.findOne().skip(random).exec(
      function (err, result) {
        console.log(result)
      })
  })
15kprogrammer
  • 67
  • 1
  • 2
  • 7
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Nick Parsons Mar 15 '19 at 11:55

4 Answers4

1

either you change your code to use promises or you just pass a callback to returnMeal and handle the response there

const returnMeal = clb => {
  Dinner1300.count().exec(function (err, count) {

    const random = Math.floor(Math.random() * count)

    Dinner1300.findOne().skip(random).exec(
      function (err, result) {
        clb(result)
      })
  })
}

returnMeal(result => {
  console.log(result);
  // move all your logic to handle the result here
})
Karim
  • 8,454
  • 3
  • 25
  • 33
0

Just assign the result to the global declared variable.

let result = null;

const returnMeal = () => {
  Dinner1300.count().exec(function (err, count) {

    const random = Math.floor(Math.random() * count)

    Dinner1300.findOne().skip(random).exec(
      function (err, result) {
        global.result = result;
        console.log(global.result)
      })
  })

Avraham
  • 928
  • 4
  • 12
0

Use module.exports

let result = null;

const returnMeal = () => {
  Dinner1300.count().exec(function (err, count) {
const random = Math.floor(Math.random() * count)

Dinner1300.findOne().skip(random).exec(
  function (err, res) {
    result = res;
    console.log(result);
  });
});

module.exports = result;
pavelbere
  • 964
  • 10
  • 21
0

Pass result in function and set value in the global scope.

var globalScope = null;
Dinner1300.count().exec(function (err, count) {
    const random = Math.floor(Math.random() * count)
    Dinner1300.findOne().skip(random).exec(
        function (err, result) {
            setValue(result)
        })
})
function setValue(result) {
    globalScope = result;
}
Paresh Barad
  • 1,544
  • 11
  • 18