Node js pass variable into request callback function
本问题已经有最佳答案,请猛点这里访问。
我希望将一个变量绑定到我的请求对象,所以当回调发生时,我可以访问这个变量。
这是图书馆:
https://github.com/request/request
这是我的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); }); } |
您已经可以访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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); } |
原始代码的问题是异步函数在
通过使用自调用函数,我们只传入应该用于函数内所有内容的