Skip to content

Instantly share code, notes, and snippets.

@jsteenkamp
Created September 4, 2018 19:59
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 jsteenkamp/311af1ecd660483cb11d009fedc32411 to your computer and use it in GitHub Desktop.
Save jsteenkamp/311af1ecd660483cb11d009fedc32411 to your computer and use it in GitHub Desktop.
Simple queue using async/await

Queue using async/await

Implement a queue using async/await.

I created a single instance, easy enough to convert to a factory if you want multiple queues or add features like timeout with configuration object.

Although this solution is simple and does not require any additional libraries I do not think it is robust. For example retries after errors or timeouts is not supported. Rather than solve these issues it makes more sense to look at proven solutions such as message/task queues.

Usage

Add processing function to queue, here I'm using sequelize ORM with my processing:

import queue from './queue';

queue.push(() =>
    models.Method.insertFile({
      file: base,
      ...data,
    })
      .then(result => console.log('db saved', base))
      .catch(err => console.error('db error', base))
  );
const queue = {
queue: [],
started: false,
push(...args) {
args.forEach(f => {
if (typeof f === 'function') {
this.queue.push(f);
}
});
if (!this.started) {
this.start();
}
},
async start() {
this.started = true;
while (this.queue.length !== 0) {
await this.queue[0]();
this.queue.shift();
}
this.started = false;
},
};
export default queue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment