2

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..

2 Answers 2

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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.