简体   繁体   中英

Javascript function not calling function passed in as parameter

I am trying to pass one function into another so that I can call it when an ajax call has finished, but I get an error saying that the function I want to call is not a function.

File1 (Loaded first)

function functionOne() {
    //Some Code
}

File2 (Loaded second and contains ajax call)

function functionTwo(functionOne) {
    functionOne();
}

functionTwo();

I get the console error of TypeError: functionOne is not a function

My question is two fold:

  1. Why is functionOne out of scope in the second function?
  2. Is this the best way of ensuring the ajax call has finished before running my first function code?

In functionTwo , you shadow functionOne as you declare it as argument: the code in functionTwo only sees this new variable, not the global one with the same name.

But your approach is the wrong one, it won't ensure the order of execution you're looking for.

jQuery's ajax function returns a promise , which is a way to deal with asynchronous functions and have some function be executed when an ajax call has finished.

If you want functionTwo to start an ajax call and then call functionOne, you may do this:

function functionOne() {
}

function functionTwo() {
    return $.ajax({ // don't forget the return
       // many parameters here
    }).then(function(data){
        // use the data here
    });
}

functionTwo().then(functionOne);

This ensures functionOne is called only after the ajax call started in functionTwo has finished.

If you want to use the old fashioned way and pass the function as argument, do it like this:

function functionOne() {
}

function functionTwo(callback) {
    $.ajax({
       // many parameters here
    }).then(function(data){
        // use the data here
    }).then(callback);
}

functionTwo(functionOne);

But it's 2015, you'd better start looking at deferreds and promises ;)

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