Skip to content

Instantly share code, notes, and snippets.

@rudasn
Created June 26, 2011 10:57
Show Gist options
  • Save rudasn/1047516 to your computer and use it in GitHub Desktop.
Save rudasn/1047516 to your computer and use it in GitHub Desktop.
Parallel, sequential ajax requests
function Parallel(oncomplete){
return {
'__requests__': [],
'__responses__': [],
'__completed__': 0,
'ajax': function(ajax_props) {
var self = this,
complete = $.isFunction(ajax_props.complete) ? ajax_props.complete : function() {},
success = $.isFunction(ajax_props.success) ? ajax_props.success : function() {},
count = this.__requests__.length;
ajax_props.complete = function() {
complete.apply(this, arguments);
self.__completed__++;
if (self.__completed__ == self.__requests__.length) {
oncomplete.apply(self, (function() {
var r = [[]];
self.__responses__.sort(function(a,b) {
return a.index - b.index;
});
for (var i=0; i < self.__responses__.length; i++) {
r[0].push(self.__responses__[i].response);
};
return r;
})());
}
};
ajax_props.success = function(response) {
success.apply(this, arguments);
var index = ajax_props.index != null ? ajax_props.index : count;
self.__responses__.push({
index: index,
response: response,
data: ajax_props.data || null
});
};
var req = $.ajax(ajax_props);
this.__requests__.push(req);
}
};
};
var fb_records = Parallel(function(data) {
console.dir(data);
var all_data = (function() {
var r = [];
$.each(data,function(a,b) {
r = r.concat(this);
});
return r;
})();
console.info(all_data);
});
// ===========
// = Example =
// ===========
test(10);
test(0);
test(40);
function test(offset){
fb_records
.ajax({
'index': offset,
'url': '/lists/',
'data': { response: 'json', offset: offset },
'complete': function(a){
console.log('complete', offset);
},
'success': function(response){
console.log('response', offset, response);
}
});
}
@rudasn
Copy link
Author

rudasn commented Jun 26, 2011

When calling the ajax function (example on line 80) you can specify an index property, which specifies the order of the data responses in the callback function (line 55).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment