Permalink
Browse files

(new task) Adds waitAll and waitAny as convenience for .and/.or

  • Loading branch information...
robotlolita committed Apr 2, 2017
1 parent fd74340 commit ea4d1c0c0f6908bbddb251af8d05848227d4b357
Showing with 65 additions and 0 deletions.
  1. +2 −0 src/data/task/index.js
  2. +23 −0 src/data/task/wait-all.js
  3. +20 −0 src/data/task/wait-any.js
  4. +20 −0 test/specs-src/data.task.js
View
@@ -16,6 +16,8 @@ const Task = require('./_task');
module.exports = {
...Task,
task: require('./task'),
waitAny: require('./race'),
waitAll: require('./parallel'),
_Task: Task,
_TaskExecution: require('./_task-execution')
};
View
@@ -0,0 +1,23 @@
//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------
const { of } = require('./_task');
const waitAll = (tasks) => {
if (tasks.length === 0) {
throw new Error('Task.waitAll() requires a non-empty array of tasks.');
}
return tasks.reduce(
(a, b) => a.and(b).map(([xs, x]) => [...xs, x]),
of([])
)
}
module.exports = waitAll;
View
@@ -0,0 +1,20 @@
//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------
const waitAny = (tasks) => {
if (tasks.length === 0) {
throw new Error(`Task.waitAny() requires a non-empty array of tasks.`);
}
return tasks.reduce((a, b) => a.or(b));
};
module.exports = waitAny;
@@ -311,6 +311,26 @@ describe('Data.Task', () => {
});
});
it('parallel()', async () => {
const result = await Task.parallel([Task.of(1), Task.of(2), Task.of(3)]).run().promise();
$ASSERT(result == [1, 2, 3]);
const result2 = await Task.parallel([Task.of(1), Task.rejected(2), Task.of(3)]).run().promise().catch(e => e);
$ASSERT(result2 == 2);
});
it('or()', async () => {
const delay = (ms) => Task.task((r) => setTimeout(() => r.resolve(ms), ms), {
cleanup: (a) => clearTimeout(a)
});
const result = await Task.race([delay(100), delay(30), delay(200)]).run().promise();
$ASSERT(result == 30);
const result2 = await Task.race([delay(100), delay(200), delay(30).swap()]).run().promise().catch(e => e == 30);
$ASSERT(result2 == true);
});
describe('#run()', () => {
it('Executes the computation for the task', () => {
let ran = false;

0 comments on commit ea4d1c0

Please sign in to comment.