Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active March 23, 2018 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/6091dc507e6819944b67074e466292d6 to your computer and use it in GitHub Desktop.
Save ccnokes/6091dc507e6819944b67074e466292d6 to your computer and use it in GitHub Desktop.
Queues async actions so they occur one after another
// class version
class Queue {
private p: Promise<any> = Promise.resolve();
push<T = any>(fn: () => Promise<any>): Promise<T> {
this.p = this.p
.then(() => fn())
.catch(err => {
console.error(err);
return fn(); //keep going to next queued
});
return this.p;
}
}
// function version
function makeQueue() {
let p: Promise<any> = Promise.resolve();
return function queue(fn) {
p = p.then(() => fn())
.catch(err => {
console.error(err);
return fn(); //keep going to next queued
});
return p;
};
}
// implement it ....
function sleep(val, dur) {
return new Promise(res => {
setTimeout(() => { res(val) }, dur);
});
}
let q = new Queue()
q.push(() => sleep(1, 1000)).then(console.log)
q.push(() => sleep(2, 500)).then(console.log)
q.push(() => sleep(3, 1)).then(console.log)
let q2 = makeQueue();
q2(() => sleep(1, 1000)).then(console.log)
q2(() => sleep(2, 500)).then(console.log)
q2(() => sleep(3, 1)).then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment