Search code examples
javascriptfor-loopcallbackinline

Javascript inline function call from callback


I have a function with a callback that checks whether or not a file exists on my server, with the result returned being either "true" or "false". My problem is that i am calling this "DoesFIleExist" function in a for-loop with the "id" calculated earlier in the function. The problem is that whenever one of the function calls is resolved and tries to call "AddResultToPage" it uses the id of the last for-loop iteration, when it should be using the id it was given when the function was called.

The "DoesFileExist" function takes a path and a callback as parameters.

Any help would be much appreciated, as i have looked online and on here but most of the answers i have found are relating to buttons and event listeners on the buttons.

DoesFileExist('/XML/'+id.trim()+'.xml',function(data) {
                        console.log(id.trim()+" "+data);
                        if (data == "true") {
                            (function () {
                                console.log("adding to page - "+id.trim());
                                AddResultToPage(id,false);
                            })();
                        }else{
                           console.log("the file does not exist");
                        }

Solution

  • Put it in a self invoking function:-

    (function(id){
    DoesFileExist('/XML/'+id.trim()+'.xml',function(data) {
                        console.log(id.trim()+" "+data);
                        if (data == "true") {
                            (function () {
                                console.log("adding to page - "+id.trim());
                                AddResultToPage(id,false);
                            })();
                        }else{
                           console.log("the file does not exist");
                        }
    })}(id)) // now, your inner code has reference to correct id due to closure
    

    What happens is, by the time your response from server is received, the for loop had been completed and id gets set to last value.

    With closure, id will refer to the value passed in the function and not the one in loop