This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5个答案)
4年前关闭。
我希望将变量绑定(bind)到我的请求对象,因此在进行回调时,我可以访问此变量。
这是图书馆:
https://github.com/request/request
这是我的代码。
原始代码的问题在于,异步函数会在
通过使用自调用函数,我们只传入应该用于该函数中所有内容的
(5个答案)
4年前关闭。
我希望将变量绑定(bind)到我的请求对象,因此在进行回调时,我可以访问此变量。
这是图书馆:
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
的值。