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

Node js pass variable into request callback function

本文关键字:请求 回调 函数 js 变量 节点      更新时间:2023-09-26

我希望将一个变量绑定到我的请求对象,以便在进行回调时可以访问此变量。

这是库: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);
  });
}

您已经可以访问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);
}

原始代码的问题在于异步函数在i值更改后很长时间内发生,在这种情况下,异步函数的每次调用都将等于cars.length

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