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 !' }))
});
via dani5
No comments:
Post a Comment