0

I can't make this code works, i'm trying to generate 5 randoms items from my DB and store them into the array (dato), but when i print it seems to be empty

/* GET users listing. */
router.get('/', function (request, response) {
    var dato = new Array();

    for(var i=0;i<7;i++){
        almuerzoSchema.findRandom({}, {}, {limit: 5}, function(err, results) {
            if (!err) {
                results.forEach(function (record) {
                    dato.push(record.nombre);
                });
            }
        });
    }
    console.log(dato);
    response.render('almuerzo.jade',{almuerzovar: dato});
});

The console.log(dato) shows:

[]

if i print "record.nombre" on console.log it shows correctly

3
  • 4
    almuerzoSchema.findRandom seems async to me! Commented Apr 29, 2016 at 5:00
  • before the for loop ends, you r trying to print the dato. For loop will run async. Commented Apr 29, 2016 at 5:02
  • 1
    Please learn how asynchronous programming Node.js works before writing any more code. There are quite a few things wrong with this route, e.g. your for loop is synchronous and is going to cause you quite a few problems. Commented Apr 29, 2016 at 5:06

1 Answer 1

2

like Rayon said, the code is async, so change it to something like this( since async, I am using Promise):

/* GET users listing. */
router.get('/', function (request, response) {
    var dato = new Array(), promises =[];

    for(var i=0;i<7;i++){
        promises.push(promisifiedFindRandom())
    }

    Promise.all(promises).then(function(){
      console.log(dato);
      response.render('almuerzo.jade',{almuerzovar: dato});
    })

    function promisifiedFindRandom(){
      return new Promise(function(resolve, reject){
          almuerzoSchema.findRandom({}, {}, {limit: 5}, function(err, results) {
              if (!err) {
                  results.forEach(function (record) {
                      dato.push(record.nombre);
                  });
                  resolve();
              }else{
                resolve();
              }
          });            
      })
    }
});

Edit: node v4+ support promise natively, for older versions, you can use polyfill/shim

Sign up to request clarification or add additional context in comments.

2 Comments

almuerzoSchema.findRandom is in a loop buddy!
I think you meant else { reject(err); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.