Created
December 1, 2017 06:05
-
-
Save stephennancekivell/ad44e14787c657fd5bd70a7e432e7dc8 to your computer and use it in GitHub Desktop.
javascript traverse cancellable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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