0

I am building the following 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') {
                 datos[i].LasValueBTC=data.result.Last;
            } else {
                 datos[i].LasValueBTC='';   
            }  
        }
    });
}

ok i get an error message: "Cannot set property 'LasValueBTC' of undefined". So i guessed that i variable is not being understood inside the callback function.. I tried without success:

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') {
                 datos[i].LasValueBTC=data.result.Last;
            } else {
                 datos[i].LasValueBTC='';   
            }  
        }
    })(i)); //and also i tried }).bind(this,i)); 
}

How is this solved?

Regards,

0

1 Answer 1

0

The problem is likely that getticker is asynchronous while the for loop is synchronous, so the value of i is probably not what you're expecting it to be by the time you access datos[i]. A simple solution for this is as follows:

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

4 Comments

thanks @glortho. After doing what you suggest 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..
Okay @Aitor that's a different (but related) question, which I can also help you with. Post that separately and let me know when it's up.
mmm i can only post every 90 minutes... :(
Okay, an easy solution to your issue can be found by using this library to call a callback once all asynchronous functions have finished: github.com/caolan/async , but you may need to spend some time becoming familiar with the library first.

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.