1

I am not writing a plugin. I am just looking for a simple clean way to let myself know when a certain function has finished executing ajax calls or whatever.

So I have this:

function doSomething() {
...
   getCauses("", query, function () {
       alert('test');  
   });
...
}

function getCauses(value, query) {
//do stuff...
}

Of course the alert never happens. I have a $.ajax call inside getCauses and would like to alert or do some action after getCauses finishes executing and then running the line of code from where the function was called.

Ideas? Thanks.

3 Answers 3

2

You first need to add the parameter to getCauses:

function getCauses(value, query, callback) {
}

Then, inside of your $.ajax call, call the callback parameter in your AJAX completion callback:

$.ajax({
    // ...
    complete: function() {
        // Your completion code
        callback();
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

Hey thanks for the quick answer. How can I detect that the type of callback is a function?
typeof(callback) == "function" - you almost answered it yourself.
I added this then if (typeof(callback) == "function") callback(); - Added the quotes, thanks :)
typeof is a language construct, not a function, therefore if(typeof callback === "function") { ... }.
0

You're passing your callback function but not executing it.

function doSomething() {
    ...
    getCauses("", query, function () {
        alert('test');  
    });
    ...
}

function getCauses(value, query, callback) {
    //do stuff...

    //stuff is done
    callback();
}

Comments

0

Just using a bit of javascript trickery, here's an implementation that will allow you to implement some default functionality, in the case that no callback is defined. This would be great if 99% of the time you want a generic callback, and then you simply want to customize it in a few places.

var my_callback = function() {
    alert('I am coming from the custom callback!');
}

var special_function(string_1, callback) {
    (callback || function() {
        // Default actions here
        alert('I am coming from the generic callback');
    })();
}

// This will alert "I am coming from the custom callback!"
special_function("Some text here", my_callback);

// This will alert "I am coming from the generic callback"
special_function("Some text here");

// This will do nothing
special_function("Some text here", function() {});

Cheers!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.