-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
1348 lines (1212 loc) · 41.9 KB
/
index.js
File metadata and controls
1348 lines (1212 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var argy = require('argy');
var debug = require('debug')('async-chainable');
var util = require('util');
// Utility functions {{{
/**
* Try and return a value from a deeply nested object by a dotted path
* This is functionally the same as lodash's own _.get() function
* @param {*} obj The array or object to traverse
* @param {string} path The path to find
* @param {*} [defaultValue=undefined] The value to return if nothing is found
*/
function getPath(obj, path, defaultValue) {
var pointer = obj;
path.split('.').every(function(slice) {
if (pointer[slice]) {
pointer = pointer[slice];
return true;
} else {
pointer = defaultValue;
return false;
}
});
return pointer;
}
/**
* Try and idenfity if the given item is a promise or is promise like
* @param {*} item The item to examine
* @returns {boolean} Whether the item looks like a promise
*/
function isPromise(item) {
if (!item) return false;
return (
(util.types && util.types.isPromise && util.types.isPromise(item))
|| (item.constructor && item.constructor.name == 'Promise')
|| (!item instanceof objectInstance && item.then && typeof item.then == 'function')
);
};
/**
* Figure out if a function declaration looks like it takes a callback
* Really this just checks the setup of a function for an argument - it cannot check if that argument is a function
* @param {function} fn The function to examine
* @returns {boolean} Whether the function LOOKS like it takes a callback
*/
function hasCallback(fn) {
var fnString = fn.toString();
// console.log('---');
// console.log('GIVEN', '>>> ' + fnString + ' <<<');
var bits, fnArgs;
if (/^async /.test(fnString)) {
// console.log('IS ASYNC');
return false; // Its an async function and should only ever return a promise
} else if (bits = /^function\s*(?:.*?)\s*\((.*?)\)/.exec(fnString)) {
// console.log('> FUNC', bits[1]);
fnArgs = bits[1];
} else if (/^\(\s*\)\s*=>/.test(fnString)) {
// console.log('ARROW (no args)');
return false;
} else if (bits = /^\s\((.*?)\)\s*?=>/.exec(fnString)) {
// console.log('> ARROW (braces)', bits[1]);
fnArgs = bits[1];
} else if (bits = /^(.*?)\s*=>/.exec(fnString)) {
// console.log('> ARROW (no braces)', bits[1]);
fnArgs = bits[1];
} else {
// console.log('> EMPTY');
return false;
}
fnArgs = fnArgs.replace(/^\s+/, '').replace(/\s+$/, ''); // Clean up args by trimming whitespace
// console.log('ARGS:', fnArgs);
return !! fnArgs;
};
// }}}
// Plugin functionality - via `use()`
var _plugins = {};
function use(module) {
module.call(this);
return this;
};
// }}}
/**
* Queue up a function(s) to execute in series
* @param {array|Object|function} The function(s) to execute
* @return {Object} This chainable object
*/
function series() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('function', function(callback) {
self._struct.push({ type: 'seriesArray', payload: [callback] });
})
.ifForm('string function', function(id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'seriesObject', payload: payload});
})
.ifForm('array', function(tasks) {
self._struct.push({ type: 'seriesArray', payload: tasks });
})
.ifForm('object', function(tasks) {
self._struct.push({ type: 'seriesObject', payload: tasks });
})
// Async library compatibility {{{
.ifForm('array function', function(tasks, callback) {
self._struct.push({ type: 'seriesArray', payload: tasks });
self.end(callback);
})
.ifForm('object function', function(tasks, callback) {
self._struct.push({ type: 'seriesObject', payload: tasks });
self.end(callback);
})
// }}}
.ifFormElse(function(form) {
throw new Error('Unknown call style for .series(): ' + form);
});
return self;
};
/**
* Queue up a function(s) to execute in parallel
* @param {array|Object|function} The function(s) to execute
* @return {Object} This chainable object
*/
function parallel() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('function', function(callback) {
self._struct.push({ type: 'parallelArray', payload: [callback] });
})
.ifForm('string function', function(id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'parallelArray', payload: payload });
})
.ifForm('array', function(tasks) {
self._struct.push({ type: 'parallelArray', payload: tasks });
})
.ifForm('object', function(tasks) {
self._struct.push({ type: 'parallelObject', payload: tasks });
})
// Async library compatibility {{{
.ifForm('array function', function(tasks, callback) {
self._struct.push({ type: 'parallelArray', payload: tasks });
self.end(callback);
})
.ifForm('object function', function(tasks, callback) {
self._struct.push({ type: 'parallelObject', payload: tasks });
self.end(callback);
})
// }}}
.ifFormElse(function(form) {
throw new Error('Unknown call style for .parallel(): ' + form);
})
return self;
};
/**
* Like parallel but only return the first, non-undefined, non-null result
* @param {string} The ID to set when the first function returns a non-undefined, non-null result
* @param {array} The functions to execute
* @return {Object} This chainable object
*/
function race() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('array', function(tasks) {
self._struct.push({ type: 'race', payload: tasks });
})
.ifForm('string array', function(id, tasks) {
self._struct.push({ type: 'race', id: arguments[0], payload: arguments[1] });
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .parallel(): ' + form);
})
return self;
};
/**
* Run an array/object though a function
* This is similar to the async native .each() function but chainable
*/
function forEach() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('array function', function(tasks, callback) {
self._struct.push({ type: 'forEachArray', payload: tasks, callback: callback });
})
.ifForm('object function', function(tasks, callback) {
self._struct.push({ type: 'forEachObject', payload: tasks, callback: callback });
})
.ifForm('string function', function(tasks, callback) {
self._struct.push({ type: 'forEachLateBound', payload: tasks, callback: callback });
})
.ifForm('number function', function(max, callback) {
self._struct.push({ type: 'forEachRange', min: 1, max: max, callback: callback });
})
.ifForm('number number function', function(min, max, callback) {
self._struct.push({ type: 'forEachRange', min: min, max: max, callback: callback });
})
.ifForm('string array function', function(output, tasks, callback) {
self._struct.push({ type: 'mapArray', output: output, payload: tasks, callback: callback });
})
.ifForm('string object function', function(output, tasks, callback) {
self._struct.push({ type: 'mapObject', output: output, payload: tasks, callback: callback });
})
.ifForm('string string function', function(output, tasks, callback) {
self._struct.push({ type: 'mapLateBound', output: output, payload: tasks, callback: callback });
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .forEach(): ' + form);
});
return self;
}
// Defer functionality - Here be dragons! {{{
/**
* Timeout handler during a wait() defer operation
* @var {number}
*/
var _deferTimeoutHandle;
/**
* Collection of items that have been deferred
* @type {array} {payload: function, id: null|String, prereq: [dep1, dep2...]}
* @access private
*/
function deferAdd(id, task, parentChain) {
var self = this;
parentChain.waitingOn = (parentChain.waitingOn || 0) + 1;
if (! parentChain.waitingOnIds)
parentChain.waitingOnIds = [];
parentChain.waitingOnIds.push(id);
self._deferred.push({
id: id || null,
prereq: parentChain.prereq || [],
payload: function(next) {
self._context._id = id;
run(self._options.context, task, function(err, value) { // Glue callback function to first arg
if (id) self._context[id] = value;
self._deferredRunning--;
if (--parentChain.waitingOn == 0) {
parentChain.completed = true;
if (self._struct.length && self._struct[self._structPointer].type == 'wait') self._execute(err);
}
self._execute(err);
}, (parentChain.prereq || []).map(function(pre) {
return self._context[pre];
}));
}
});
};
function _deferCheck() {
var self = this;
if (self._options.limit && self._deferredRunning >= self._options.limit) return; // Already over limit
self._deferred = self._deferred.filter(function(item) {
if (self._options.limit && self._deferredRunning >= self._options.limit) {
return true; // Already over limit - all subseqent items should be left in place
}
if (
item.prereq.length == 0 || // No pre-reqs - can execute now
item.prereq.every(function(dep) { // All pre-reqs are satisfied
return self._context.hasOwnProperty(dep);
})
) {
self._deferredRunning++;
setTimeout(item.payload);
return false;
} else { // Can't do anything with self right now
// Timeout functionality {{{
if (_deferTimeoutHandle) clearTimeout(_deferTimeoutHandle);
if (self._options.timeout) {
_deferTimeoutHandle = setTimeout(self._options.timeoutHandler.bind(self), self._options.timeout);
}
// }}}
return true;
}
});
};
// }}}
/**
* Queue up a function(s) to execute as deferred - i.e. dont stop to wait for it
* @param {array|Object|function} The function(s) to execute as a defer
* @return {Object} This chainable object
*/
function defer() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('function', function(callback) {
self._struct.push({ type: 'deferArray', payload: [callback] });
})
.ifForm('string function', function(id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'deferObject', payload: payload });
})
.ifForm('array', function(tasks) {
self._struct.push({ type: 'deferArray', payload: tasks });
})
.ifForm('object', function(tasks) {
self._struct.push({ type: 'deferObject', payload: tasks });
})
.ifForm('array function', function(preReqs, callback) {
self._struct.push({ type: 'deferArray', prereq: preReqs, payload: [callback] });
})
.ifForm('string string function', function(preReq, id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'deferObject', prereq: [preReq], payload: payload });
})
.ifForm('array string function', function(preReqs, id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'deferObject', prereq: preReqs, payload: payload });
})
.ifForm('string array function', function(id, preReqs, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'deferObject', prereq: preReqs, payload: payload });
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .defer():' + form);
});
return self;
};
/**
* Queue up an wait point
* This stops the execution queue until its satisfied that dependencies have been resolved
* @param {array,...} The dependencies to check resolution of. If omitted all are checked
* @return {Object} This chainable object
*/
function wait() {
var payload = [];
// Slurp all args into payload
argy(arguments)
.getForm()
.split(',')
.forEach(function(type, offset) {
switch (type) {
case '': // Blank arguments - do nothing
// Pass
break;
case 'string':
payload.push(args[offset]);
break;
case 'array':
payload.concat(args[offset]);
break;
default:
throw new Error('Unknown argument type passed to .wait(): ' + type);
}
});
this._struct.push({ type: 'wait', payload: payload });
return this;
};
/**
* Queue up a timeout setter
* @param {number|function|false} Either a number (time in ms) of the timeout, a function to set the timeout handler to or falsy to disable
* @return {Object} This chainable object
*/
function timeout(newTimeout) {
var self = this;
argy(arguments)
.ifForm('', function() {
self._struct.push({ type: 'timeout', delay: false });
})
.ifForm('boolean', function(setTimeout) {
if (setTimeout) throw new Error('When calling .timeout(Boolean) only False is accepted to disable the timeout');
self._struct.push({ type: 'timeout', delay: false });
})
.ifForm('number', function(delay) {
self._struct.push({ type: 'timeout', delay: delay });
})
.ifForm('function', function(callback) {
self._struct.push({ type: 'timeout', callback: callback });
})
.ifForm('number function', function(delay, callback) {
self._struct.push({ type: 'timeout', delay: delay, callback: callback });
})
.ifForm('function number', function(delay, callback) {
self._struct.push({ type: 'timeout', delay: delay, callback: callback });
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .timeout():' + form);
});
return self;
}
/**
* The default timeout handler
* This function displays a simple error message and also fires the 'timeout' hook
*/
function _timeoutHandler() {
var currentTaskIndex = this._struct.findIndex(function(task) { return ! task.completed });
if (!currentTaskIndex < 0) {
console.log('Async-Chainable timeout on unknown task');
console.log('Full structure:', this._struct);
} else {
console.log('Async-Chainable timeout: Task #', currentTaskIndex + 1, '(' + this._struct[currentTaskIndex].type + ')', 'elapsed timeout of', this._options.timeout + 'ms');
}
this.fire('timeout');
}
/**
* Queue up a limit setter
* @param {number|null|false} Either the number of defer processes that are allowed to execute simultaniously or falsy values to disable
* @return {Object} This chainable object
*/
function setLimit(setLimit) {
this._struct.push({ type: 'limit', payload: setLimit });
return this;
};
/**
* Queue up a context setter
* @param {Object} newContext The new context to pass to all subsequent functions via `this`
* @return {Object} This chainable object
*/
function setContext(newContext) {
this._struct.push({ type: 'context', payload: newContext });
return this;
};
/**
* Queue up a varable setter (i.e. set a hash of variables in context)
* @param {string} The named key to set
* @param {*} The value to set
* @return {Object} This chainable object
*/
function set() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('string scalar|array|object|date|regexp|null', function(id, value) {
var payload = {};
payload[id] = value;
self._struct.push({ type: 'set', payload: payload });
})
.ifForm('object', function(obj) {
self._struct.push({ type: 'set', payload: obj });
})
.ifForm('function', function(callback) {
self._struct.push({ type: 'seriesArray', payload: [callback] });
})
.ifForm('string function', function(id, callback) {
var payload = {};
payload[id] = callback;
self._struct.push({ type: 'seriesObject', payload: payload});
})
.ifForm(['string', 'string undefined'], function(id) {
var payload = {};
payload[id] = undefined;
self._struct.push({ type: 'set', payload: payload });
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .set():' + form);
});
return self;
};
/**
* Set a context items value
* Not to be confused with `set()` which is the chainable external visible version of this
* Unlike `set()` this function sets an item of _context immediately
* @access private
* @see _setRaw()
*/
function _set() {
var self = this;
argy(arguments)
.ifForm('', function() {})
.ifForm('string scalar|array|object|date|regexp|null', function(id, value) {
self._setRaw(id, value);
})
.ifForm('object', function(obj) {
for (var key in obj)
self._setRaw(key, obj[key]);
})
.ifForm('string function', function(id, callback) {
self._setRaw(id, callback.call(this));
})
.ifForm('function', function(callback) { // Expect func to return something which is then processed via _set
self._set(callback.call(this));
})
.ifForm(['string', 'string undefined'], function(id) {
self._setRaw(id, undefined);
})
.ifFormElse(function(form) {
throw new Error('Unknown call style for .set():' + form);
});
return self;
}
/**
* Actual raw value setter
* This function is the internal version of _set which takes exactly two values, the key and the value to set
* Override this function if some alternative _context platform is required
* @param {string} key The key within _context to set the value of
* @param {*} value The value within _context[key] to set the value of
* @access private
*/
function _setRaw(key, value) {
this._context[key] = value;
return this;
}
/**
* Internal function executed at the end of the chain
* This can occur either in sequence (i.e. no errors) or a jump to this position (i.e. an error happened somewhere)
* @access private
*/
function _finalize(err) {
// Sanity checks {{{
if (this._struct.length == 0) return; // Finalize called on dead object - probably a defer() fired without an wait()
if (this._struct[this._struct.length - 1].type != 'end') {
throw new Error('While trying to find an end point in the async-chainable structure the last item in the this._struct does not have type==end!');
return;
}
// }}}
var self = this;
this.fire('end', function(hookErr) {
self._struct[self._struct.length-1].payload.call(self._options.context, err || hookErr);
if (self._options.autoReset) self.reset();
});
};
/**
* Internal function to execute the next pending queue item
* This is usually called after the completion of every asyncChainable.run call
* @access private
*/
function _execute(err) {
var self = this;
if (err) return this._finalize(err); // An error has been raised - stop exec and call finalize now
if (!self._executing) { // Never before run this object - run fire('start') and defer until it finishes
self._executing = true;
return self.fire.call(self, 'start', self._execute.bind(self));
}
do {
var redo = false;
if (self._structPointer >= self._struct.length) return this._finalize(err); // Nothing more to execute in struct
self._deferCheck(); // Kick off any pending deferred items
var currentExec = self._struct[self._structPointer];
// Sanity checks {{{
if (!currentExec.type) {
throw new Error('No type is specified for async-chainable structure at offset ' + self._structPointer);
return self;
}
// }}}
self._structPointer++;
// Skip step when function supports skipping if the argument is empty {{{
if (
[
'parallelArray', 'parallelObject',
'forEachArray', 'forEachObject',
'seriesArray', 'seriesObject',
'deferArray', 'deferObject',
'set'
].indexOf(currentExec.type) > -1 &&
(
!currentExec.payload || // Not set OR
(argy.isType(currentExec.payload, 'array') && !currentExec.payload.length) || // An empty array
(argy.isType(currentExec.payload, 'object') && !Object.keys(currentExec.payload).length) // An empty object
)
) {
currentExec.completed = true;
redo = true;
continue;
}
// }}}
switch (currentExec.type) {
case 'forEachRange':
var iterArray = Array(currentExec.max - currentExec.min + 1).fill(false);
self.runArray(iterArray.map(function(v, i) {
var val = self._context._item = currentExec.min + i;
var index = self._context._key = i;
return function(next) {
if (currentExec.translate) val = currentExec.translate(val, index, iterArray.length);
run(self._options.context, currentExec.callback, next, [val, index, iterArray.length]);
};
}), self._options.limit, function(err) {
currentExec.completed = true;
self._execute(err);
});
break;
case 'forEachArray':
self.runArray(currentExec.payload.map(function(item, iter) {
self._context._item = item;
self._context._key = iter;
return function(next) {
run(self._options.context, currentExec.callback, next, [item, iter]);
};
}), self._options.limit, function(err) {
currentExec.completed = true;
self._execute(err);
});
break;
case 'forEachObject':
self.runArray(Object.keys(currentExec.payload).map(function(key) {
return function(next) {
self._context._item = currentExec.payload[key];
self._context._key = key;
run(self._options.context, currentExec.callback, function(err, value) {
self._set(key, value); // Allocate returned value to context
next(err);
}, [currentExec.payload[key], key]);
};
}), self._options.limit, function(err) {
currentExec.completed = true;
self._execute(err);
});
break;
case 'forEachLateBound':
if (!currentExec.payload || !currentExec.payload.length) { // Payload is blank
// Goto next chain
currentExec.completed = true;
redo = true;
break;
}
var resolvedPayload = self.getPath(self._context, currentExec.payload);
if (!resolvedPayload) { // Resolved payload is blank
// Goto next chain
currentExec.completed = true;
redo = true;
break;
}
// Replace own exec array with actual type of payload now we know what it is {{{
if (argy.isType(resolvedPayload, 'array')) {
currentExec.type = 'forEachArray';
} else if (argy.isType(resolvedPayload, 'object')) {
currentExec.type = 'forEachObject';
} else {
throw new Error('Cannot perform forEach over unknown object type: ' + argy.getType(resolvedPayload));
}
currentExec.payload = resolvedPayload;
self._structPointer--; // Force re-eval of this chain item now its been replace with its real (late-bound) type
redo = true;
// }}}
break;
case 'mapArray':
var output = new Array(currentExec.payload.length);
self.runArray(currentExec.payload.map(function(item, iter) {
self._context._item = item;
self._context._key = iter;
return function(next) {
run(self._options.context, currentExec.callback, function(err, value) {
if (err) return next(err);
output[iter] = value;
next();
}, [item, iter]);
};
}), self._options.limit, function(err) {
currentExec.completed = true;
self._set(currentExec.output, output);
self._execute(err);
});
break;
case 'mapObject':
var output = {};
self.runArray(Object.keys(currentExec.payload).map(function(key) {
return function(next) {
self._context._item = currentExec.payload[key];
self._context._key = key;
run(self._options.context, currentExec.callback, function(err, value, outputKey) {
output[outputKey || key] = value;
next(err);
}, [currentExec.payload[key], key]);
};
}), self._options.limit, function(err) {
currentExec.completed = true;
self._set(currentExec.output, output);
self._execute(err);
});
break;
case 'mapLateBound':
if (!currentExec.payload || !currentExec.payload.length) { // Payload is blank
// Goto next chain
currentExec.completed = true;
redo = true;
break;
}
var resolvedPayload = self.getPath(self._context, currentExec.payload);
if (!resolvedPayload) { // Resolved payload is blank
// Goto next chain
currentExec.completed = true;
redo = true;
break;
}
// Replace own exec array with actual type of payload now we know what it is {{{
if (argy.isType(resolvedPayload, 'array')) {
currentExec.type = 'mapArray';
} else if (argy.isType(resolvedPayload, 'object')) {
currentExec.type = 'mapObject';
} else {
throw new Error('Cannot perform map over unknown object type: ' + argy.getType(resolvedPayload));
}
currentExec.payload = resolvedPayload;
self._structPointer--; // Force re-eval of this chain item now its been replace with its real (late-bound) type
redo = true;
// }}}
break;
case 'parallelArray':
case 'seriesArray':
self.runArray(currentExec.payload.map(function(task) {
return function(next) {
run(self._options.context, task, next);
};
}), currentExec.type == 'parallelArray' ? self._options.limit : 1, function(err) {
currentExec.completed = true;
self._execute(err);
});
break;
case 'seriesObject':
case 'parallelObject':
self.runArray(Object.keys(currentExec.payload).map(function(key) {
return function(next) {
run(self._options.context, currentExec.payload[key], function(err, value) {
self._set(key, value); // Allocate returned value to context
next(err);
});
};
}), currentExec.type == 'parallelObject' ? self._options.limit : 1, function(err) {
currentExec.completed = true;
self._execute(err);
});
break;
case 'race':
var hasResult = false;
var hasError = false;
self.runArray(currentExec.payload.map(function(task) {
return function(next) {
run(self._options.context, task, function(err, taskResult) {
if (err) {
hasError = true
next(err, taskResult);
} else if (!hasResult && !hasError && taskResult !== null && typeof taskResult !== 'undefined') {
self._set(currentExec.id, taskResult); // Allocate returned value to context
hasResult = true;
next('!RACEDONE!', taskResult); // Force an error to stop the run() function
} else {
next(err, taskResult);
}
});
};
}), self._options.limit, function(err, val) {
currentExec.completed = true;
// Override race finish error as it was just to stop the race and not a real one
if (err == '!RACEDONE!') return self._execute();
self._execute(err);
});
break;
case 'deferArray':
currentExec.payload.forEach(function(task) {
self._deferAdd(null, task, currentExec);
});
redo = true;
break;
case 'deferObject':
Object.keys(currentExec.payload).forEach(function(key) {
self._deferAdd(key, currentExec.payload[key], currentExec);
});
redo = true;
break;
case 'wait': // Wait can operate in two modes, either payload=[] (examine all) else (examine specific keys)
if (!currentExec.payload.length) { // Check all tasks are complete
if (self._struct.slice(0, self._structPointer - 1).every(function(stage) { // Examine all items UP TO self one and check they are complete
return stage.completed;
})) { // All tasks up to self point are marked as completed
if (_deferTimeoutHandle) clearTimeout(_deferTimeoutHandle);
currentExec.completed = true;
redo = true;
} else {
self._structPointer--; // At least one task is outstanding - rewind to self stage so we repeat on next resolution
}
} else { // Check certain tasks are complete by key
if (currentExec.payload.every(function(dep) { // Examine all named dependencies
return !! self._context[dep];
})) { // All are present
if (_deferTimeoutHandle) clearTimeout(_deferTimeoutHandle);
currentExec.completed = true;
redo = true;
} else {
self._structPointer--; // At least one dependency is outstanding - rewind to self stage so we repeat on next resolution
}
}
break;
case 'limit': // Set the options.limit variable
self._options.limit = currentExec.payload;
currentExec.completed = true;
redo = true; // Move on to next action
break;
case 'timeout': // Set the timeout function or its timeout value
if (currentExec.delay === false) { // Disable
self._options.timeout = false;
} else {
// Set the callback if one was passed
if (currentExec.callback) self._options.timeoutHandler = currentExec.callback;
// Set the delay if one was passed
if (currentExec.delay) self._options.timeout = currentExec.delay;
}
currentExec.completed = true;
redo = true; // Move to next action
break;
case 'context': // Change the self._options.context object
self._options.context = currentExec.payload ? currentExec.payload : self._context; // Set context (if null use internal context)
currentExec.completed = true;
redo = true; // Move on to next action
break;
case 'set': // Set a hash of variables within context
Object.keys(currentExec.payload).forEach(function(key) {
self._set(key, currentExec.payload[key]);
});
currentExec.completed = true;
redo = true; // Move on to next action
break;
case 'end': // self should ALWAYS be the last item in the structure and indicates the final function call
this._finalize();
break;
default:
if (this._plugins[currentExec.type]) { // Is there a plugin that should manage this?
this._plugins[currentExec.type].call(this, currentExec);
} else {
throw new Error('Unknown async-chainable exec type: ' + currentExec.type);
}
return;
}
} while (redo);
};
// runArray() - dispatch an array of callbacks (with a parallel run limit) and run a callback when complete {{{
/**
* Internal function to run an array of functions (usually in parallel)
* Functions can be run in series by passing limit=1
* NOTE: Since this function is the central bottle-neck of the application code here is designed to run as efficiently as possible. This can make it rather messy and unpleasent to read in order to maximize thoughput.
* Series execution can be obtained by setting limit = 1
* @param {array} tasks The array of tasks to execute
* @param {number} limit The limiter of tasks (if limit==1 tasks are run in series, if limit>1 tasks are run in limited parallel, else tasks are run in parallel)
* @param {function} callback(err) The callback to fire on finish
* @return {Object} This chainable object
*/
function runArray(tasks, limit, callback) {
var self = this;
var nextTaskOffset = 0;
var running = 0;
var err;
// Empty
if (!tasks || !tasks.length) return callback();
// Timeout functionality {{{
var _timeoutTimer;
var resetTimeout = function(setAgain) {
if (_timeoutTimer) clearTimeout(_timeoutTimer);
if (setAgain) _timeoutTimer = self._options.timeout ? setTimeout(self._options.timeoutHandler.bind(self), self._options.timeout) : null;
};
// }}}
var taskFinish = function(taskErr, taskResult) {
if (taskErr) err = taskErr;
--running;
if (err && !running) {
resetTimeout(false);
callback(err);
} else if (err) { // Has an err - stop allocating until we empty
resetTimeout(false);
// Pass
} else if (!running && nextTaskOffset > tasks.length - 1) { // Finished everything
resetTimeout(false);
callback(err);
} else if (nextTaskOffset < tasks.length) { // Still more to alloc
running++;
resetTimeout(true);
setTimeout(tasks[nextTaskOffset++].bind(this._context, taskFinish));
}
};
var maxTasks = limit && limit <= tasks.length ? limit : tasks.length;
for (var i = 0; i < maxTasks; i++) {
running++;
setTimeout(tasks[i].bind(this, taskFinish));
}
resetTimeout(true); // Start initial timeout
nextTaskOffset = maxTasks;
return this;
}
/**
* Run a single function, promise return, promise factory or any other combination - then a callback when finished
* Take a function reference and treat it as a callback style function
* If the function returns a promise this behaviour is transformed into a callback style function
*
* This function accepts all types of input functions:
* - callback functions (e.g. `next => ...`)
* - async functions (e.g. `async ()=> ...`)
* - promise functions (e.g. `new Promise(resolve => ...)`)
* - promise factories (e.g. `()=> new Promise(resolve => ...)`)
*
* @param {Object} context The context object to pass to the function
* @param {function|Promise} fn The function to run or the promise to resolve
* @param {function} finish The function to call when finished
* @param {array} [args] Additional arguments to pass when calling the function
*
* @example Run a regular callback function - if func is callback its just passed through, if its a promise its mapped normally
* run(func, thenFunc)
*/
function run(context, fn, finish, args) {
// Argument mangling {{{
if (typeof context == 'function') { // called as run(fn, finish, args);
args = finish;
finish = fn;
fn = context;
context = this;
}
// }}}
if (isPromise(fn)) { // Given a promise that has already resolved?
fn
.then(function(value) {