JavaScript callback after function call

So let's say that I have this function:

function a(message) { alert(message); } 

And I want to have a callback after the warning window displays. Something like that:

 a("Hi.", function() {}); 

I am not sure how to have a callback inside the function that I am calling.

(I just use the warning window as an example)

Thanks!

+6
javascript callback
source share
3 answers

There is no special syntax for callbacks, just pass a callback function and call it inside your function.

 function a(message, cb) { console.log(message); // log to the console of recent Browsers cb(); } a("Hi.", function() { console.log("After hi..."); }); 

Output:

 Hi. After hi... 
+23
source share

You can add an if statement to check if the callback function has been added or not. Thus, you can use this function also without a callback.

 function a(message, cb) { alert(message); if (typeof cb === "function") { cb(); } } 
+5
source share

Here is the code that will warn first and then the second. Hope this is what you asked for.

 function basic(callback) { alert("first..."); var a = "second..."; callback(a); } basic(function (abc) { alert(abc); }); 
0
source share

All Articles