Skip to content

Instantly share code, notes, and snippets.

@AtsushiSuzuki
Last active August 5, 2016 16:14
Show Gist options
  • Save AtsushiSuzuki/54efd9b85322fbd3d708774b6836af4d to your computer and use it in GitHub Desktop.
Save AtsushiSuzuki/54efd9b85322fbd3d708774b6836af4d to your computer and use it in GitHub Desktop.
ES2015 function queue
"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