Ilya Karnaukhov
Ilya Karnaukhov

Reputation: 3975

Javascript - make function tell the caller when function is finished

So let's say I'm calling a function like so:

some_function('pages',{attr1: 1, attr2: 2},function(){
    alert('the function is ready!');
}

Now how do I set up the "some_function()" function in order to return to the caller that it is ready and make the alert go off?

Thanks :)

Upvotes: 0

Views: 94

Answers (3)

Anish Gupta
Anish Gupta

Reputation: 2226

I think you mean callbacks. Maybe something like this:

function some_function(param1, param2, callback) {

    // normal code here...

    if ( typeof callback === 'function' ) { // make sure it is a function or it will throw an error
        callback();
    }
}

Usage:

some_function("hi", "hello", function () {
    alert("Done!");
}); 
/* This will do whatever your function needs to do and then,
when it is finished, alert "Done!" */

Note: Put your return after the if clause.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227280

Assuming the signature for some_function looks like this:

function some_function(name, data, callback)

You just need to call callback when you're ready to.

function some_function(name, data, callback){
    // do whatever
    if(typeof callback === 'function'){
        callback(); // call when ready
    }
}

Upvotes: 1

ioseb
ioseb

Reputation: 16951

Do you mean something like this?

function some_function(type, options, callback) {
  if (some_condition) {
    callback();
  }
}

Upvotes: 1

Related Questions