Skip to content

Instantly share code, notes, and snippets.

@behnammodi
Last active November 19, 2018 13:46
Show Gist options
  • Save behnammodi/ee2d7c0669763ccf86ff1a772f3e1d80 to your computer and use it in GitHub Desktop.
Save behnammodi/ee2d7c0669763ccf86ff1a772f3e1d80 to your computer and use it in GitHub Desktop.
async queue in javascript
let count = 0;
let running = false;
const queue = {};
const addTask = task => {
queue[count++] = task;
if (running === false) runTasks();
}
const runTasks = async () => {
running = true;
for (let key = 0; key < count; key++) {
const func = queue[key];
delete queue[key];
await func();
}
running = false;
}
addTask(() => {
return new Promise(done =>
setTimeout(() => {
console.log(1);
done();
}, 1000)
)
})
addTask(() => {
console.log(2);
})
addTask(() => {
return new Promise(done =>
setTimeout(() => {
console.log(3);
done();
}, 1000)
)
})
addTask(() => {
console.log(4);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment