1

I got some help using .promise().done on an xml parser, here. This method is fine if you combine the .promise().done() with the parser function. What I really wanted to do, though, was define the parser function separately up top, then execute it later in the code, and the apply the promise().done() to it there:

var xmlparse = function(){
  $.get("file.xml), {}. function(xml) {
     $('photo',xml).each(function(i){
       ...
       array filling
       .....
      });
   });
});

xmlparse().promise().done(function(){...

I've learned that line above doesn't work; I need to pass an object that the original function acted on. If xmlparse() was changing a div, for example, I'd say $('div').promise().done(). But what exactly can being passed for an XML parser that doesn't change any HTML structure? (This goes back to the original solution; I'm glad it works, but I don't understand quite why.) Any help's appreciated.

Community
  • 1
  • 1

1 Answers1

0

The way to chain things with promises is .then, we can compose this ourselves on top of a callback API but we don't have to in this case since $.get already returns a promise.

The point of promises is to give us back desirable properties (like returning and throwing) of synchronous code, the way to chain operations is via the .then mwrhos.

var xmlparse = function(){
  // we return a promise here
  return $.get("file.xml).then(function(xml) { // .then is used to continue
     $('photo',xml).each(function(i){
       ...
       array filling
       .....
      });
      return array; // returning from a `.then` will cause it to be the return value of 
      // the whole promise chain, promises compose. 
   });
};

Now, our xmlparse is a promise returning function so we can do:

xmlparse().done(function(result){...
    // access result here
});

If we want to chain it to other asynchronous operations we can change .then to .then and chain on.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504