Simple async queue in javascript 
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.
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
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') }); |
01-'14 Simple function logger in JS
02-'13 Getting started on Firefox OS apps with AngularJS
Reacties
Interessant! Tip voor het vervolg: noem je variabelen wat logischer dan n, q etc. Kostte me nu iets meer puzzelwerk 

Agreed.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
Reageren is niet meer mogelijk