节点js将变量传递给请求回调函数

Jim*_*ray 3 javascript asynchronous node.js

我希望将一个变量绑定到我的请求对象,所以当回调发生时,我可以访问这个变量.

这是图书馆:https: //github.com/request/request

这是我的代码.

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

}
Run Code Online (Sandbox Code Playgroud)

aar*_*ard 9

你已经可以进入i,成熟的采取,关闭!

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);
}
Run Code Online (Sandbox Code Playgroud)

原始代码的问题是异步函数在i值更改后很久就会发生,在这种情况下cars.length,对于异步函数的每次调用它都是相等的.

通过使用自调用函数,我们只传入i应该用于函数内所有内容的值.