Skip to content

Commit

Permalink
Add canceler to Task.all, and tests. Issue dojo#260.
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobroufa committed May 23, 2017
1 parent f777ae6 commit 0c7c244
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/async/Task.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Thenable } from '@dojo/shim/interfaces';
import { Executor } from '@dojo/shim/Promise';
import ExtensiblePromise, { ListOfPromises, DictionaryOfPromises } from './ExtensiblePromise';
import { Iterable } from '@dojo/shim/iterator';
import { Iterable, forOf, isIterable, isArrayLike } from '@dojo/shim/iterator';

/**
* Describe the internal state of a task.
Expand Down Expand Up @@ -72,7 +72,28 @@ export default class Task<T> extends ExtensiblePromise<T> {
static all<T>(iterable: T | Thenable<T>): Task<T[]>;
static all<T>(iterable: ListOfPromises<T>): Task<T[]>;
static all<T>(iterable: DictionaryOfPromises<T> | ListOfPromises<T>): Task<any> {
return <Task<T>> super.all(iterable);
return new Task<T>((resolve, reject) => {
super.all(iterable).then(<any> resolve, <any> reject);
}, () => {
if (isIterable(iterable) || isArrayLike(iterable)) {
forOf(iterable, (promiseLike: any) => {
if (isTask(promiseLike)) {
promiseLike.cancel();
}
});
}
else {
const promiseKeys = Object.keys(iterable);

promiseKeys.forEach((key: any) => {
const promiseLike = iterable[ key ];

if (isTask(promiseLike)) {
promiseLike.cancel();
}
});
}
});
}

/**
Expand Down
40 changes: 40 additions & 0 deletions tests/unit/async/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,46 @@ function addPromiseTests(suite: any, Promise: any) {
Promise.all(iterable).then(dfd.callback(function (value: number[]) {
assert.notStrictEqual(value, iterable);
}));
},

'cancelable': {
'isIterable': function (this: any) {
let pending: any[] = [];

for (let i = 0; i < 3; i++) {
pending[i] = new Promise(function () {});
}

let tasks = Promise.all(pending);

tasks.cancel();

tasks.then(() => {
pending.forEach((task) => {
assert.strictEqual(task.state, State.Canceled, 'Task should have Canceled state');
});
});
},
'isObject': function (this: any) {
let pending = <any> {};

for (let i = 0; i < 3; i++) {
pending[i] = new Promise(function () {});
}

let tasks = Promise.all(pending);

tasks.cancel();

tasks.then(() => {
let keys = Object.keys(pending);

keys.forEach((key) => {
let task = pending[key];
assert.strictEqual(task.state, State.Canceled, 'Task should have Canceled state');
});
});
}
}
};

Expand Down

0 comments on commit 0c7c244

Please sign in to comment.