prongs
prongs

Reputation: 9606

dojo two xhr requests and callback function fired only when both are complete

Is there a way of handling multiple xhr requests like this? for one xhr, there's a function builtin but for multiple requests?

Upvotes: 3

Views: 1390

Answers (3)

mschr
mschr

Reputation: 8641

A dojo.xhr returns a dojo.Deferred, a Deferred is a wrapper for callbacks and like. So key function in your case would be dojo.xhr({parameters}).then(callbackFunction).

Whilst we often want to achieve parallel XHR by the an easy shortcut of polls and counters, Dojo has also though of this, there is as Craig informs DeferredList;

You will fire two times an XHR, each call returns a handler, reference those. Create a list with those references as arguments, collected in an array. Then as final touch, append a 'then' call on the list,

var dXhr1 = dojo.xhrGet({ url: ... });
var dXhr2 = dojo.xhrGet({ url: ... });
var dList = new dojo.DeferredList([dXhr1, dXhr2]);
dList.then(function(arrayOfValues) { 
    var res = "Result: succes?+"arrayOfValues[0][0].toString()+":"+arrayOfValues[0][1]+", "+
    succes?+"arrayOfValues[1][0].toString()+":"+arrayOfValues[1][1]+";
console.log(res);
});

or chained

new dojo.DeferredList([
     dojo.xhrGet({ url: ... }),
     dojo.xhrGet({ url: ... })
]).then(function(res) { console.log(res); });

Upvotes: 6

Craig Swing
Craig Swing

Reputation: 8162

A DeferredList will do what you need.

http://dojotoolkit.org/reference-guide/1.7/dojo/DeferredList.html

Upvotes: 4

ChrisG
ChrisG

Reputation: 114

Couldn't you fire a callback that hits a function with an internal counter? When that counter reaches 2, then both callbacks have completed?

Upvotes: 1

Related Questions