简体   繁体   中英

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:

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:

 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.

The issue is because you declare loadCallback outside of the function. As such you overwrite that assignment in every iteration of your loop.

To fix this just use the callback argument directly. 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) }); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM