Simple async queue in javascript nl

Door creator1988 op donderdag 2 januari 2014 13:51 - Reacties (2)
Categorie: Frontend, Views: 4.956

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.
JavaScript:
1
2
3
4
5
6
7
8
9
10
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:
JavaScript:
1
2
3
4
5
6
7
8
var input = 'sometext'
var q = input.split('').map(function(c) {
  return function(n) {
    sendKey(c).then(n);
  };
});

queue(q, function() { console.log('done') });

Volgende: Simple function logger in JS 01-'14 Simple function logger in JS
Volgende: Getting started on Firefox OS apps with AngularJS 02-'13 Getting started on Firefox OS apps with AngularJS

Reacties


Door Tweakers user WeeJeWel, donderdag 2 januari 2014 15:59

Interessant! Tip voor het vervolg: noem je variabelen wat logischer dan n, q etc. Kostte me nu iets meer puzzelwerk :p

Door Tweakers user TheKirk, dinsdag 7 januari 2014 07:56

WeeJeWel schreef op donderdag 02 januari 2014 @ 15:59:
Interessant! Tip voor het vervolg: noem je variabelen wat logischer dan n, q etc. Kostte me nu iets meer puzzelwerk :p
Agreed.

Reageren is niet meer mogelijk