Thursday, 8 September 2016

javascript - Node js pass variable into request callback function




I am looking to bind a variable to my request object so when the callback is made I have access to this variable.



Here is the library:
https://github.com/request/request



Here is my code.



var request = require('request');    
for (i = 0; i < cars.length; i++) {



request({
headers: { 'Content-Type': 'application/json'},
uri: 'https://example.com',
method: 'POST',
body: '{"clientId": "x", "clientSecret": "y"}'
},
function(err, res, body){
// I want to put the correct i here.

// This outputs cars.length almost everytime.
console.log(i);
});

}

Answer



You already have access to the i, ripe for the taking, with a closure!



var request = require('request');    

for (i = 0; i < cars.length; i++) {

(function(i){
request({
headers: { 'Content-Type': 'application/json'},
uri: 'https://example.com',
method: 'POST',
body: '{"clientId": "myea1r4f7xfcztkrb389za1w", "clientSecret": "f0aQSbi6lfyH7d6EIuePmQBg"}'
},
function(err, res, body){

// I want to put the correct i here.
// This outputs cars.length almost everytime.
console.log(i);
});
})(i);
}


The problem with your original code was that the async function happens long after the i value has changed, in this case it will be equal cars.length for each call of the async function.




By using a self-calling function, we pass in only the value of i that should be used for everything within the function.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...