This post was originally published on Coding Glamour.

Normally I fall back to caolan's async module, but I'm not in a node.js environment and I needed a simple async queue with concurrency 1; which can be done in a one liner.

var q = [
  function a(n) { console.log('a'), setTimeout(n, 30); },
  function b(n) { console.log('b'), setTimeout(n, 10); }
];
function queue(q, n) {
  q.length ? q.shift()(queue.bind(this, q, n)) : n();
}
queue(q, function() { console.log('done') });

You could use arguments.callee rather than queue to bind to the current function, but it has been deprecated since ES5.

It's also easy to use it with promises, let's say I have a function |sendKey| that returns a promise and I want to send a string char by char:

var input = 'sometext'
var q = input.split('').map(function(c) {
  return function(n) {
    sendKey(c).then(n);
  };
});
queue(q, function() { console.log('done') });