Ox.Async: fix return value

This commit is contained in:
rolux 2013-12-04 16:49:42 +01:00
parent 6e5105025c
commit 9554d22fa8

View file

@ -31,7 +31,7 @@ Ox.get = function(url, callback) {
/*@
Ox.getAsync <f> Runs an asynchonous loader for an array of URLs
(urls, get, callback) -> <u> undefined
urls <s|a> URL or array of either URLs or arrays of URLs
urls <s|a> URL or array of URLs or arrays of such arrays
Multiple URLs in the same array will be processed simultaneously, but
multiple arrays of URLs will be processed in that order.
get <f> Asynchronous function that loads a URL (for example Ox.get)
@ -42,33 +42,28 @@ Ox.getAsync <f> Runs an asynchonous loader for an array of URLs
code <n> Status code
text <s> Status text
callback <f> Callback function
results <o|null> Results
results <o|{}> Results, or empty on error
Keys are file names, values are results
errors <o|null> Errors, or null
errors <o|{}> Errors, or empty on success
Keys are file names, values are error objects
@*/
Ox.getAsync = function(urls, get, callback) {
urls = Ox.clone(Ox.makeArray(urls));
urls = Ox.makeArray(urls);
var errors = {}, i = 0, n = urls.length, results = {};
function done() {
callback && callback(
n == 1 ? results[urls[0]] : results,
n == 1 ? errors[urls[0]] : Ox.some(errors, function(error) {
return error !== null;
}) ? errors : null
);
callback && callback(filter(results), filter(errors));
}
function iterate() {
var url = urls.shift();
Ox.getAsync(url, get, function(result, error) {
results[url] = result;
errors[url] = error;
urls.length ? iterate() : done();
function extend(object, value, urls) {
value !== null && Ox.extend.apply(null, [object].concat(
urls.length === 1 ? [urls[0], value] : [value]
));
}
function filter(object) {
return n == 1 ? object[urls[0]] : Ox.filter(object, function(value) {
return value !== null;
});
}
if (urls.some(Ox.isArray)) {
iterate();
} else {
function getParallel() {
urls.forEach(function(url) {
get(url, function(result, error) {
results[url] = result;
@ -77,6 +72,15 @@ Ox.getAsync = function(urls, get, callback) {
});
});
}
function getSerial() {
var url = urls.shift();
Ox.getAsync(url, get, function(result, error) {
extend(results, result, url);
extend(errors, error, url);
urls.length ? getSerial() : done();
});
}
urls.some(Ox.isArray) ? getSerial() : getParallel();
};
/*@