Like forEachAsync, or Promise.all(), but handling a bounded number of items at any given time.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

111 lines
4.0 KiB

(function(exports) {
"use strict";
var batchAsync =
exports.batchAsync || require("./batchasync.js").batchAsync;
function testBatch() {
var timeouts = [100, 80, 20, 500, 50, 30, 200, 300];
console.info(timeouts);
var tasks = timeouts.map(function(timeout, i) {
return function() {
return promiseTimeout(timeout).then(function() {
//console.log("task:", i, timeouts[i]);
return i + ":" + timeouts[i];
});
};
});
var len = tasks.length;
return batchAsync(4, tasks, function(task) {
return task();
})
.then(function(results) {
console.info("results:", results);
if (len !== results.length) {
throw new Error("result set too small");
}
if (results.join(" ") !== results.sort().join(" ")) {
throw new Error("result set out-of-order");
}
})
.then(function() {
return batchAsync(4, [], "not a function").then(function() {
console.info("Handled ZERO tasks correctly.");
});
})
.then(function() {
return batchAsync(4, timeouts, function(x) {
return x;
}).then(function(results) {
if (results.join(" ") !== timeouts.join(" ")) {
console.error(results);
throw new Error("sync result set out-of-order");
}
console.info("Handled sync tasks correctly.");
});
})
.then(function() {
return batchAsync(4, tasks, function(task) {
if (0 === Math.floor(Math.random() * 2) % 2) {
throw new Error("any async error will do");
}
return task();
})
.then(function(results) {
console.log(results);
var e = new Error("async rejection should not pass!");
e.FAIL = true;
throw e;
})
.catch(function(e) {
if (e.FAIL) {
throw e;
}
console.info("Pass: Exception thrown when expected");
});
})
.then(function() {
return batchAsync(4, timeouts, function() {
if (0 === Math.floor(Math.random() * 2) % 2) {
throw new Error("any sync error will do");
}
return null;
})
.then(function(/*results*/) {
var e = new Error("should not pass sync exception!");
e.FAIL = true;
throw e;
})
.catch(function(e) {
if (e.FAIL) {
throw e;
}
})
.then(function() {
// wait for the tasks the error left dangling to print their message
console.info("Pass: Promise rejected when expected");
return promiseTimeout(1000);
});
});
}
function promiseTimeout(timeout) {
return new Promise(function(resolve) {
setTimeout(resolve, timeout);
});
}
testBatch()
.then(function() {
console.info("PROBABLY PASSED");
console.info(
"We tested what could be tested. Do the results make sense?"
);
})
.catch(function(e) {
console.error("FAIL!");
console.error(e);
process.exit(500);
});
})("undefined" !== typeof window ? window : module.exports);