Comparing version 1.1.0 to 2.0.0
{ | ||
"name": "dumb-queue", | ||
"version": "1.1.0", | ||
"version": "2.0.0", | ||
"description": "A simple queue that handles async functions with a wait time.", | ||
@@ -5,0 +5,0 @@ "main": "src/queue.js", |
@@ -22,10 +22,10 @@ dumb-queue | ||
// The callback must return a promise so`the queue know when the task has finished. | ||
queue(() => someAsyncSlowAction1()) | ||
queue.add(() => someAsyncSlowAction1()) | ||
// ... | ||
// Further in your code. | ||
queue(() => someAsyncSlowAction2()) | ||
queue.add(() => someAsyncSlowAction2()) | ||
// ... | ||
// You can, of course, use non-async functions with the help of `async` which will | ||
// always return a promise. | ||
queue(async () => someSyncSlowAction3()) | ||
queue.add(async () => someSyncSlowAction3()) | ||
@@ -32,0 +32,0 @@ // Wait until the queue is empty. |
module.exports = waitTime => { | ||
const queue = [] | ||
const obj = callback => { | ||
// Add the new callback. | ||
queue.push(async () => { | ||
await callback() | ||
await new Promise(resolve => setTimeout(resolve, waitTime)) | ||
// Unqueue and call the next callback. | ||
if (queue.length >= 1) { | ||
queue.shift() | ||
if (queue.length) { | ||
queue[0]() | ||
return { | ||
add(callback) { | ||
// Add the new callback. | ||
queue.push(async () => { | ||
await callback() | ||
await new Promise(resolve => setTimeout(resolve, waitTime)) | ||
// Unqueue and call the next callback. | ||
if (queue.length >= 1) { | ||
queue.shift() | ||
if (queue.length) { | ||
queue[0]() | ||
} | ||
} | ||
}) | ||
// Run the current callback directly if it's the only element in the queue. | ||
if (queue.length == 1) { | ||
queue[0]() | ||
} | ||
}) | ||
// Run the current callback directly if it's the only element in the queue. | ||
if (queue.length == 1) { | ||
queue[0]() | ||
}, | ||
wait() { | ||
// Wait until the queue is empty. | ||
return new Promise(resolve => { | ||
const interval = setInterval( | ||
() => { | ||
if (queue.length == 0) { | ||
clearInterval(interval) | ||
resolve() | ||
} | ||
}, | ||
1 | ||
) | ||
}) | ||
} | ||
} | ||
// Add a method to wait until the queue is empty. | ||
obj.wait = () => { | ||
return new Promise(resolve => { | ||
const interval = setInterval( | ||
() => { | ||
if (queue.length == 0) { | ||
clearInterval(interval) | ||
resolve() | ||
} | ||
}, | ||
1 | ||
) | ||
}) | ||
} | ||
return obj | ||
} |
2430
40