From 9554d22fa8a008dcdcdeca29e94d3dc0c16d6708 Mon Sep 17 00:00:00 2001 From: rolux Date: Wed, 4 Dec 2013 16:49:42 +0100 Subject: [PATCH] Ox.Async: fix return value --- source/Ox/js/Request.js | 42 ++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/source/Ox/js/Request.js b/source/Ox/js/Request.js index caa6fe19..4c39e0ad 100644 --- a/source/Ox/js/Request.js +++ b/source/Ox/js/Request.js @@ -31,7 +31,7 @@ Ox.get = function(url, callback) { /*@ Ox.getAsync Runs an asynchonous loader for an array of URLs (urls, get, callback) -> undefined - urls URL or array of either URLs or arrays of URLs + urls 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 Asynchronous function that loads a URL (for example Ox.get) @@ -42,33 +42,28 @@ Ox.getAsync Runs an asynchonous loader for an array of URLs code Status code text Status text callback Callback function - results Results + results Results, or empty on error Keys are file names, values are results - errors Errors, or null + errors 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(); }; /*@