S
S
soolver2017-05-17 07:32:44
JavaScript
soolver, 2017-05-17 07:32:44

How to make a nodejs parallel request?

There was a problem, up to the end I can not understand how to work with asynchronous languages.
The function works, gives me the desired object, but only after the second request to the server.
On the first request, it returns an empty array, then fills it, and on the second request, it 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 !' }))
 
  });

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question