Last active
August 5, 2016 16:14
-
-
Save AtsushiSuzuki/54efd9b85322fbd3d708774b6836af4d to your computer and use it in GitHub Desktop.
ES2015 function queue
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
"use strict"; | |
class Queue { | |
constructor() { | |
this.running = false; | |
this.items = []; | |
} | |
enqueue(fn) { | |
return new Promise((resolve, reject) => { | |
this.items.push(() => { | |
return fn().then(resolve, reject); | |
}); | |
this.run(); | |
}); | |
} | |
run() { | |
if (!this.running && 0 < this.items.length) { | |
this.running = true; | |
this.items.shift()().then(() => { | |
this.running = false; | |
this.run(); | |
}, () => { | |
this.running = false; | |
this.run(); | |
}); | |
} | |
} | |
} | |
module.exports = Queue; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment