Skip to content

Instantly share code, notes, and snippets.

@stephennancekivell
Created December 1, 2017 06:05
Show Gist options
  • Save stephennancekivell/ad44e14787c657fd5bd70a7e432e7dc8 to your computer and use it in GitHub Desktop.
Save stephennancekivell/ad44e14787c657fd5bd70a7e432e7dc8 to your computer and use it in GitHub Desktop.
javascript traverse cancellable
/*
* traverse cancellable takes an Array of promise's running them in parallel returning a single promise of their result and cancel function.
*
* @inputThunks Array[() => Promise[A]] an array of promises not yet started, thunks () => Promise
* @returns Object {
* promise: Promise[Array[A]]
* cancel: Function() to cancel
* }
*/
export function traverseCancellable(inputThunks) {
let running = true;
function go(remaining, acc) {
if (!running) {
return Promise.reject('cancelled');
} else if (remaining.length <= 0) {
return acc;
} else {
const [head, ...tail] = remaining;
return head().then(headResult => {
return go(tail, [...acc, headResult]);
});
}
}
const promise = go(inputThunks, []);
const self = {
promise: promise,
cancel: () => {
running = false;
},
catch: (fn) => {
promise.catch(fn);
return self;
}
};
return self;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment