Created
June 14, 2018 08:10
-
-
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.
This file contains hidden or 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
// 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