Last active
April 26, 2018 19:18
-
-
Save Meir017/830453b9ff43d312ff7de51fa36dca53 to your computer and use it in GitHub Desktop.
nodejs promise 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
class PromiseQueue { | |
constructor(tasks = []) { | |
this.task = Promise.resolve(); | |
for (const { func, args } of tasks) { | |
this.run(func, ...args); | |
} | |
} | |
run(func, ...args) { | |
return new Promise((resolve, reject) => { | |
this.task = this.task.then(async () => { | |
try { | |
const response = await func(...args); | |
resolve(response); | |
} catch (error) { | |
reject(error); | |
} | |
return Promise.resolve(); | |
}); | |
}); | |
} | |
all() { | |
return this.task; | |
} | |
} | |
(async function () { | |
const results = []; | |
function usingConstructor() { | |
const queue = new PromiseQueue([ | |
{ func: printDelayed, args: ['first', 500] }, | |
{ func: printDelayed, args: ['second', 400] }, | |
{ func: printDelayed, args: ['third', 300] }, | |
{ func: d => Promise.reject(d), args: ['failed'] }, | |
{ func: printDelayed, args: ['fourth', 200] }, | |
{ func: printDelayed, args: ['fifth', 100] }, | |
]); | |
return queue; | |
} | |
function usingFunction() { | |
const queue = new PromiseQueue(); | |
queue.run(printDelayed, 'first', 500); | |
queue.run(printDelayed, 'second', 400); | |
queue.run(printDelayed, 'third', 300); | |
queue.run(d => Promise.reject(d), 'failed').catch(e => results.push(e)); | |
queue.run(printDelayed, 'fourth', 200); | |
queue.run(printDelayed, 'fifth', 100); | |
return queue; | |
} | |
const queue = usingFunction(); | |
function printDelayed(message, delay) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log(message); | |
results.push(message); | |
resolve(message); | |
}, delay); | |
}); | |
} | |
await queue.all(); | |
console.log('results', results); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment