Skip to content

Instantly share code, notes, and snippets.

Forked from spudly/abortable.js
Last active Apr 21, 2016
What would you like to do?
Abort your promises!
const abortable = (func) => (...args) => {
let aborted = false;
const abort = () => { aborted = true; };
const promise = new Promise((resolve, reject) => {
const resolveIfNotAborted = resolution => {
if (aborted) {
reject(Error('promise aborted'));
func(...args).then(resolveIfNotAborted, reject);
return {promise, abort};
const names = ['John', 'Mary', 'William', 'Helen', 'James', 'Dorothy', 'Robert', 'Margaret', 'Joseph', 'Ruth', 'George', 'Anna', 'Charles', 'Mildred', 'Edward', 'Elizabeth', 'Frank', 'Frances', 'Walter', 'Marie', 'Thomas', 'Evelyn', 'Henry', 'Alice', 'Paul', 'Florence', 'Harold', 'Virginia', 'Albert', 'Rose', 'Raymond', 'Lillian', 'Richard', 'Louise', 'Arthur', 'Catherine', 'Harry', 'Edna', 'Louis', 'Gladys', 'Ralph', 'Ethel', 'Clarence', 'Irene', 'Donald', 'Josephine', 'Carl', 'Ruby', 'Willie', 'Grace', 'Howard', 'Thelma', 'Jack', 'Martha', 'Fred', 'Eleanor', 'David', 'Hazel', 'Kenneth', 'Lucille', 'Francis', 'Edith', 'Roy', 'Gertrude', 'Earl', 'Annie', 'Joe', 'Pauline', 'Samuel', 'Esther', 'Lawrence', 'Doris', 'Anthony', 'Clara', 'Ernest', 'Beatrice', 'Stanley', 'Emma', 'Michael', 'Ann', 'Alfred', 'Bertha', 'Herbert', 'Julia', 'Eugene', 'Bernice', 'Andrew', 'Agnes', 'Leonard', 'Marjorie', 'Elmer', 'Elsie', 'Leo', 'Sarah', 'Peter', 'Katherine', 'Russell', 'Ida', 'Bernard', 'Marion', 'Herman', 'Lois', 'Frederick', 'Eva', 'Edwin', 'Anne', 'Norman', 'Jean', 'Daniel', 'Bessie', 'Chester', 'Pearl', 'Lester', 'Viola', 'Floyd', 'Mabel', 'Melvin', 'Laura', 'Leroy', 'Myrtle', 'Vincent', 'Nellie', 'Clifford', 'Betty', 'Clyde', 'Kathryn', 'Theodore', 'Jessie', 'Charlie', 'Stella', 'Lloyd', 'Willie', 'Sam', 'Minnie', 'Philip', 'Vera', 'Milton', 'Alma', 'Benjamin', 'Sylvia', 'Woodrow', 'Jane', 'Lewis', 'Ella', 'Martin', 'Lucy', 'Ray', 'Lillie', 'Marvin', 'Lena', 'Victor', 'Genevieve', 'Oscar', 'Jennie', 'Alvin', 'Mattie', 'Cecil', 'Leona', 'Stephen', 'Blanche', 'Gerald', 'Vivian', 'Jesse', 'Barbara', 'Vernon', 'Violet', 'Lee', 'Marguerite', 'Leon', 'Mae', 'Morris', 'Ellen', 'Edgar', 'Rita', 'Gordon', 'Charlotte', 'Sidney', 'Opal', 'Everett', 'Marian', 'Glenn', 'Carrie', 'Willard', 'Theresa', 'Claude', 'Velma', 'Maurice', 'Juanita', 'Harvey', 'Wilma', 'Wilbur', 'Beulah', 'Arnold', 'Hattie', 'Alexander', 'Emily', 'Max', 'Fannie', 'Irving', 'Sophie'];
const fetchUsers = abortable(({startsWith}) => {
const users = names.filter(name => name[0] == startsWith);
return new Promise(resolve => {
setTimeout(resolve.bind(null, users), 500)
let promise, abort;
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'].forEach(letter => {
if (promise) {
({promise, abort} = fetchUsers({startsWith: letter}));
promise.then(::console.log).catch((e) => {
if (e.message !== 'promise aborted') {
throw e;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment