Created
June 26, 2011 10:57
-
-
Save rudasn/1047516 to your computer and use it in GitHub Desktop.
Parallel, sequential ajax requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).