[英]Calling JS function multiple times with different callbacks executes only the last callback every time
I have a function that I call multiple times passing it different callback function as an argument.我有一个函数,我多次调用它,将不同的回调函数作为参数传递给它。 I need to execute the passed callback when the function is called, however it always executes the last callback as many times as the function is called.我需要在调用函数时执行传递的回调,但是它总是执行与调用函数一样多的最后一个回调。
Here is an example:下面是一个例子:
var loadCallback = 'undefined';
function callMe (callback) {
loadCallback = callback;
// some code here
loadCallback();
}
Then I'm calling it 3 times like this:然后我像这样调用它 3 次:
callMe(function(){
var test1 = function () {console.log('test1')}
test1();
// another code that has to be executed, but only the one from the last call is executed every time
});
callMe(function(){
var test2 = function () {console.log('test2')}
test2();
// another code that has to be executed, but only the one from the last call is executed every time
});
callMe(function(){
var test3 = function () {console.log('test3')}
test3();
// another code that has to be executed, but only the one from the last call is executed every time
});
In an SO snippet:在 SO 片段中:
var loadCallback; function callMe(callback) { loadCallback = callback; loadCallback(); } callMe(function() { var test1 = function() { console.log('test1') } test1(); }); callMe(function() { var test2 = function() { console.log('test2') } test2(); }); callMe(function() { var test3 = function() { console.log('test3') } test3(); });
And in the console I see:在控制台中我看到:
test3
test3
test3
instead of:代替:
test1
test2
test3
Why is this happening and how to fix it?为什么会发生这种情况以及如何解决? I'm searching in Google for over an hour now and I can't find a solution.我现在在 Google 上搜索了一个多小时,但找不到解决方案。
The issue is because you declare loadCallback
outside of the function.问题是因为您在函数之外声明了loadCallback
。 As such you overwrite that assignment in every iteration of your loop.因此,您在循环的每次迭代中都会覆盖该分配。
To fix this just use the callback
argument directly.要解决此问题,只需直接使用callback
参数即可。 Also note that you don't need to wrap the callback function multiple times when you define it.另请注意,定义回调函数时无需多次包装回调函数。 Try this:尝试这个:
function callMe(callback) { // other logic... callback(); } for (var i = 1; i <= 3; i++) { callMe(function() { console.log('test' + i) }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.