-1

The function works, gives me the required object, but only after the second request to the server. At the first request, returns an empty array, then fills it, and at the second request already issues

'use strict';

const user2 = require('../models/base');
var array =  [];
var i =0;



exports.getEda = email => 
  
  new Promise((resolve,reject) => {

     user2.count().exec(function(err, count){

  var random = Math.floor(Math.random() * count);
  var calories = 2500;

  test(calories);

    
  function test(calories, random) {
    user2.findOne().skip(random).exec(
    function (err, result) {
      random = Math.floor(Math.random() * count);
      
      var stringify = JSON.stringify(result);
      var jsonContent = JSON.parse(stringify);   
      calories = calories - jsonContent.calories;
      console.log(calories);
      if (calories > 0){
      test(calories, random);
      } 
        
      array[i] = result;
        i++;  
        
  });   
  }
        
  console.log(array);
      
})

    .then(eda => resolve(array))
    .catch(err => reject({ status: 500, message: 'Internal Server Error !' }))
 
  });
dani5
  • 1
  • 1
    Please format/indent the code properly. – str May 18 '17 at 12:49
  • 1
    Please add a question to your question. Clarify what's your problem and what you tried to solve it. Ahow some effort/ – Clijsters May 18 '17 at 12:53
  • I need to get some objects from Mongo and add them to the array. In response to the request, I must send this array – dani5 May 18 '17 at 12:59
  • Avoid the [`Promise` constructor antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi May 18 '17 at 13:02
  • Why is this tagged async-await? – Bergi May 18 '17 at 13:02

1 Answers1

0

You forget about return:

...
return new Promise((resolve,reject) => {
...
Sergaros
  • 821
  • 1
  • 5
  • 14