I know that ajax calls are asynchronous but there are situations like some synchronous execution is needed. For Example,
loadMyProfile();
editMyProfile();
These are two javascript functions I want loadMyprofile() should be executed completely and after that it should call editMyProfile(). But that is not happening because its asynchronous.I have heard like callbacks will be the best to handle this situation. So could anyone please explain about callbacks and a sample associated with this example?
Any help will be appreciated!
Thanks,
Karthik
JavaScript isn’t asynchronous. The language itself defines no asynchronous features at all. The two function calls you’ve shown will be done in order, first
loadMyProfile, theneditMyProfile. JavaScript does have language features that make asynchronous programming a lot easier, but it doesn’t itself define any asynchronous operations.There are two major asynchronous features of the environment in which JavaScript runs in the web browser, though, which (forgive me) I assume is the environment in which you’re trying to use it.
The first and probably most relevant is that, by default, ajax calls are asynchronous. So for instance, if your
loadMyProfilefunction is making an ajax call, the function will return before that ajax call is completed. This is a feature (and quite a useful one!) of theXMLHttpRequestobject.The second is the
setTimeoutandsetIntervalfunctions available on thewindowobject in a web browser.setTimeoutschedules a function to be called after a timeout (e.g., asynchronously).setIntervalschedules a function to be called repeatedly, at an interval.A callback is simply a function that gets called when something else happens. The
XMLHttpRequestobject accepts functions it will call on completion, etc. The functions that you use withsetTimeoutandsetIntervalare callbacks. Event handlers are another kind of callback, called when the relevant event occurs in the DOM.Looking at your example:
Let’s assume that
loadMyProfiledoes indeed do an asynchronous ajax call to load the profile information from a server and then display it on the page, e.g.:(That code is syntactically correct, it just uses made-up functions to avoid blinding you with details.)
Now, if we want to be able to call
editMyProfilewhen the profile has finished loading, we need to makeloadMyProfileaccept a callback function that it will call when the profile has been loaded:Then we use it like this:
Note there that I don’t have
()aftereditMyProfile. I’m not calling it directly in that statement, I’m passing a reference to it intoloadMyProfile, which will call it when the appropriate time comes.