-1

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 ?

4
  • download().then(parseXML).then(processParsedXMLFile). Commented May 15, 2015 at 10:08
  • any library to be included ? Commented May 15, 2015 at 10:14
  • Probably not depending on your environment. Commented May 15, 2015 at 10:15
  • What would you consider simplest? Commented May 18, 2015 at 4:56

2 Answers 2

0

You can use callbacks

load(params , function(){
  download(params, function(){
      parseXML(params, function(){
        processParsedXMLFile(params, function(){
           ...
        })
      })
   })
})
Sign up to request clarification or add additional context in comments.

5 Comments

I would add also that the callbacks usually accept a parameter of the result, or sometimes two parameters (error and result), or sometimes there are two callbacks (one for error and one for success). Bottom line - READ THE DOCS of the async function and pay attention to the signature of the callback.
also, note that usually the IO methods are async (eg. download resource, or wait for user event) but "process" and "parse" methods are usually sync. Again - read the documentation of the functions you are using.
Great answer. Oh wait, it's 2015.
I didn't think that promises were that easy to explain to someone who clearly doesn't know about asynchronous JavaScript.
@Maroun I think promises are easier to explain than callbacks.
0

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:

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*/ });

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.