I have a load() function, Inside that I want to call a function say download(), which download a xml file. Once download is completed , I have to call a function say parseXML() which parses the downloaded xml file. Once the parsing is completed, I have to call another function say processParsedXMLFile(). Can you please guide me how can I achieve this in the simplest possible way ?
2 Answers
You can use callbacks
load(params , function(){
download(params, function(){
parseXML(params, function(){
processParsedXMLFile(params, function(){
...
})
})
})
})
5 Comments
Two common approaches exist for asynchronous code in JavaScript - callbacks and promises.
There are many posts on SO discussing callback and Javascript callback after json parse shows good example with detailed explanation.
For promises: http://wiki.commonjs.org/wiki/Promises/A and https://www.promisejs.org/ are good starting place to read about Promises which are more common now to write asynchronous code in JavaScript.
Depending on where you run you script you may need to include packages/libraries to have support for promises:
- NodeJS - install corresponding package ("promise", "q",...)
- WinJS -promises are natively supported. Info - WinJS.Promise and guide Asynchronous programming in JavaScript, there are also many question on SO covering different aspects like WinJS, return a promise from a function which may or may not be async
- For regular browsers using jQuery's implementation is common practice -[]jQuery.promise](http://api.jquery.com/promise/). With broader availability of ES6 compatible browsers you will not need additional libraries - MDM Promise - ES6
With promises would look like following (assuming each of the calls returns promise that is fulfilled when operation finishes):
download()
.then(function(data){/* parse XML here */})
.then(function(data){/* process parsed XML*/ });
download().then(parseXML).then(processParsedXMLFile).