如何在请求调用时将值传递给回调函数? [英] How to pass values to a callback function at the time of the request call?
本文介绍了如何在请求调用时将值传递给回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况:
var foo = [ 0, 1, 2 ]
for (var i in foo) {
Asyncstuff.get(URI).on('response', function(res) { console.log(i); } });
}
因为.on('response',...)被调用以异步方式,输出很可能是
Because the .on('response',...) is called in an asynchronous manner, the output will most likely be
2
2
2
在.get()是否有可能传递 i 的值调用回调函数?
Is there a possibility to pass the value of i at the time the .get() is called to the callback function?
推荐答案
你需要一个闭包。有比这更好的方法,但这应该清楚地证明这个概念:
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);
}
这篇关于如何在请求调用时将值传递给回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文