How to pass values to a callback function at the time of the request call?

后端 未结 3 1147
执念已碎
执念已碎 2021-01-07 08:32

I have the following situation:

var foo = [ 0, 1, 2 ]
for (var i in foo) {
    Asyncstuff.get(URI).on(\'response\', function(res) { console.log(i); } });
}
<         


        
3条回答
  •  温柔的废话
    2021-01-07 09:13

    You need a closure. There are better ways than this, but this should clearly demonstrate the concept:

    var foo = [ 0, 1, 2 ]
    for (var i in foo) {
        (function(i){
            Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
        })(i);
    }
    

提交回复
热议问题