Egidi
Egidi

Reputation: 1776

Scope issue calling a callback function inside a loop in node.js

With the help of glortho in this thread i built this code:

for(var i=0;i<datos.length;i++){
   bittrex.getticker(datos[i].Currency, function(err, data){
        if (err){
            console.log('ERROR:', err);
            return 'ERROR:'+ err;
        } else {
            if (data.message!='INVALID_MARKET') {
                 this.LasValueBTC=data.result.Last;
            } else {
                 this.LasValueBTC='';   
            }  
        }
    }.bind(datos[i]));
}

The problem is that outside the callback function the datos array is not updated...As it is written at the moment if i console.log(this) inside the function works great and this.LastValueBTC exists in my json, but outside the function if i console.log(datos) after the loop, the LastValueBTC does not exist..and i need to do a res.send(datos) after the loop..

Upvotes: 2

Views: 976

Answers (2)

randomness
randomness

Reputation: 1447

Go through this article http://www.richardrodger.com/2011/04/21/node-js-how-to-write-a-for-loop-with-callbacks/#.VTXnFa2eDGc

It gives a good conceptual overview on what happens if you put functions inside for loop

Upvotes: 1

Barış Uşaklı
Barış Uşaklı

Reputation: 13532

What you need to do is wait for all the callbacks to complete and then call res.send.

var count = datos.length;
for(var i=0;i<datos.length;i++){
   bittrex.getticker(datos[i].Currency, function(err, data){
        if (err){
            console.log('ERROR:', err);
            return 'ERROR:'+ err;
        } else {
            if (data.message!='INVALID_MARKET') {
                 this.LasValueBTC=data.result.Last;
            } else {
                 this.LasValueBTC='';   
            }  
            count--;
            if (count === 0) {
                res.send(datos);
            }
        }
    }.bind(datos[i]));
}

Or using async

async.each(datos, function(dato, next) {
     bittrex.getticker(dato.Currency, function(err, data) {
        if (err){
            console.log('ERROR:', err);
            next(err);
        } else {
            if (data.message!='INVALID_MARKET') {
                 dato.LasValueBTC = data.result.Last;
            } else {
                 dato.LasValueBTC='';   
            }  
            next();
        }
    });
}, function(err) {
   res.send(datos);
});

Upvotes: 2

Related Questions