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 authored and maier49 committed Nov 3, 2017
1 parent e987183 commit 4876bbf
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, unwrapPromises } 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 @@ -149,7 +149,28 @@ export default class Task<T> extends ExtensiblePromise<T> {
* @returns An extensible promise
*/
static all<T>(iterable: DictionaryOfPromises<T> | ListOfPromises<T>): Task<any> {
return super.all(iterable) as Task<any>;
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 @@ -382,6 +382,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 4876bbf

Please sign in to comment.