Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node js pass variable into request callback function [duplicate]

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);
  });

}
like image 937
Jimmy Scray Avatar asked May 25 '26 12:05

Jimmy Scray


1 Answers

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.

like image 151
aaronofleonard Avatar answered May 28 '26 00:05

aaronofleonard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!