How can I make a jquery-like ajax promise that has additional parameters when it succeeds?

49 views
Skip to first unread message

Peter Zingg

unread,
Aug 8, 2014, 1:46:07 AM8/8/14
to bac...@googlegroups.com
Code snippet:

// passed the url from an event stream, return a promise to load the document at the url
function loadXmlDoc(url) {
  return Bacon.fromPromise($.ajax({url: url, dataType: xml}));
}

// create a stream that gets maps to a valid url when button is clicked.
var s1 = $('#load').asEventStream('click').map(getUrlToLoad);

// transform to a new stream that promises an ajax load of the document
var s2 = s1.flatMapLatest(loadXmlDoc);
  
// now do something with the document
s2.onValue(function(xml) { parseDoc(xml); } )

It's all working, but I'd like the parseDoc() function to also receive the url (location)
of the document that was loaded.  But s2 is a promise that "evaluates" to
just the xml document. I'm afraid I'm new at promises and the jquery 
ajax call. I guess there must be a way to rewrite loadXmlDoc so that the
promise that succeeds by returning an array or a dict, like:

{ data: xmlDoc, location: url  }



mkaemmerer

unread,
Aug 8, 2014, 11:28:40 AM8/8/14
to bac...@googlegroups.com
I can think of a couple ways to do this.

1) You can modify the result of the promise by using the method `then`.

function loadXmlDoc(url){
var promise = $.ajax({url: url, dataType: 'xml'})
.then(function(xml){ return {location: url, data: xml}; });
return Bacon.fromPromise(promise);
}

2) Similarly, you could modify the result of the event stream using `map`.

function loadXmlDoc(url){
var promise = $.ajax({url: url, dataType: 'xml'});
return Bacon.fromPromise(promise)
.map(function(xml){ return {location: url, data: xml}; });
Reply all
Reply to author
Forward
0 new messages