Last active
March 23, 2018 19:12
-
-
Save ccnokes/6091dc507e6819944b67074e466292d6 to your computer and use it in GitHub Desktop.
Queues async actions so they occur one after another
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
// 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