Skip to content

Instantly share code, notes, and snippets.

@moqmar
Created June 14, 2018 08:10
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 moqmar/ad75424217ffe22882c7643a3c8a11d0 to your computer and use it in GitHub Desktop.
Save moqmar/ad75424217ffe22882c7643a3c8a11d0 to your computer and use it in GitHub Desktop.
Completely promise-based queue that works with functions returning promises and normal values.
// Completely promise-based queue that works with functions returning promises and normal values.
/*
function doSomething() {
return new Promise(y => setTimeout(() => y(), 3000));
}
// Using the singleton
for (let i = 0; i < 10; i++) Q(() => doSomething()).then(() => console.log(i));
// As an object (multiple queues)
var q = new Q();
for (let i = 0; i < 10; i++) q(() => doSomething()).then(() => console.log(i));
*/
function Q(fn, ...args) {
// Call as constructor
if (this.constructor === Q && typeof this.functions === "undefined") {
const obj = { functions: [], paused: true, is: Q };
obj.work = Q.work.bind(obj);
return Q.bind(obj);
} else if (typeof this.is === "undefined" || this.is !== Q) {
return Q._singleton(fn, ...args);
}
return new Promise(function(resolve, reject) {
this.functions.push([fn, args, resolve, reject]);
if (this.paused) this.work();
}.bind(this));
}
Q.work = function work() {
if (this.functions.length) {
this.paused = false;
const first = this.functions.shift();
Promise.resolve(first[0](...first[1]))
.then(function(resolve, value) {
resolve(value);
this.work();
}.bind(this, first[2]))
.catch(function(reject, value) {
reject(value);
this.work();
}.bind(this, first[3]))
} else {
this.paused = true;
}
}
Q._singleton = new Q();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment