-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChainLoading.js
717 lines (671 loc) · 27.8 KB
/
ChainLoading.js
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
(function(window, undefined) {
var CompletedMap = window.WeakMap,
slice = [].slice, //from: http://stackoverflow.com/questions/120804/difference-between-array-slice-and-array-slice/121302#121302
indexOf = [].indexOf,
noopThis = function() { return this; };
//polyfill for WeakMap (we only need set/get)
if (CompletedMap === undefined) {
CompletedMap = function() {
var arr = [];
this.has = function(k) {
var i = -1;
if (k !== undefined) { //only search if they actually gave us something to search for
i = arr.length - 1;
}
while (i >= 0) {
if (arr[i] === k) {
break;
}
i--;
}
return i > -1;
};
this.set = function(k) {
if (k !== undefined) {
arr.push(k);
}
};
};
}
if (indexOf === undefined) {
indexOf = function(search, fromIndex) {
var len = this.length,
i = +fromIndex || 0;
if (len === 0 || i >= len) {
return -1;
}
//apparently passing Infinity for fromIndex means we should start at 0?
if (!isFinite(i)) {
i = 0;
}
if (i < 0) {
i = Math.max(len - Math.abs(i), 0);
}
while (i < len) {
if (this[i] === search) {
return i;
}
i++;
}
return -1;
};
}
function callFuncsOptimized(funcs, argsPassed, ctx) {
var args = argsPassed || {length: 0},
i;
switch (args.length) {
case 0:
for (i = 0; i < funcs.length; i++) {
funcs[i].call(ctx);
}
break;
case 1:
for (i = 0; i < funcs.length; i++) {
funcs[i].call(ctx, args[0]);
}
break;
case 2:
for (i = 0; i < funcs.length; i++) {
funcs[i].call(ctx, args[0], args[1]);
}
break;
case 3:
for (i = 0; i < funcs.length; i++) {
funcs[i].call(ctx, args[0], args[1], args[2]);
}
break;
default:
for (i = 0; i < funcs.length; i++) {
funcs[i].apply(ctx, args);
}
break;
}
}
function LevelContainer(chain, ready) {
this.chain = chain;
this.ready = ready || false; //ready means that we should call any callbacks as soon as they finish
this.completed = true; //completed means we have finished ALL deferreds assigned to us (by default we have finished them all)
this.state = '';
this.dfds = [];
this.failCallbacks = [];
this.nextLevel = null;
this.prevLevel = null;
this.failedArgs = null;
}
LevelContainer.prototype.newGroup = function(dfds, stateOnFail, globalCallbacks, completedDeferreds) {
if (this.state === '') { //if we haven't finished yet and we just added a new group, we're NOT complete
this.completed = false;
}
var o = {s: 0, r: this.ready},
level = this,
group;
this.dfds.push(o);
group = new GroupedDfd(dfds, function(s, g, args) {
o.g = g; //store the group on the object, so we can call complete on it
o.s = 1;
switch (s) {
case 'resolved':
//don't overwrite with resolved if we already got a state
if (level.state === '') {
level.state = 'resolved';
}
break;
case 'rejected':
//don't overwrite stopped
if (level.state !== 'stopped') {
level.state = stateOnFail;
level.failedArgs = args;
}
break;
}
level.complete(args);
}, globalCallbacks, completedDeferreds);
return group;
};
LevelContainer.prototype.requireDeferreds = function(dfds, globalCallbacks, completedDeferreds) {
return this.newGroup(dfds, 'rejected', globalCallbacks, completedDeferreds).promise;
};
LevelContainer.prototype.optionalDeferreds = function(dfds, globalCallbacks, completedDeferreds) {
return this.newGroup(dfds, 'ignored', globalCallbacks, completedDeferreds).promise;
};
//this is expected to be called only for the most recent level, otherwise we need to fix failedArgs
LevelContainer.prototype.addFailCallback = function(f) {
//if we already failed, immediately call
//README states that fail() is called whenever previous levels failed
if (this.state === 'ignored' || this.state === 'rejected') {
callFuncsOptimized([f], this.failedArgs, this.chain);
} else if (!this.completed || this.state === '') {
this.failCallbacks.push(f);
}
};
LevelContainer.prototype.removeFailCallback = function(f) {
var index = indexOf.call(this.failCallbacks, f);
if (index !== -1) {
this.failCallbacks.splice(index, 1);
}
};
LevelContainer.prototype.complete = function(originalArgs) {
if (this.ready !== true) {
return;
}
//if the state is "ignored" then we need to reject the deferreds still attached to this level
//the normalizedState returns "resolved" since to *everything else* its resolved
var normalizedState = this.state === 'ignored' ? 'rejected' : this.normalizedState(),
i;
for (i = 0; i < this.dfds.length; i++) {
if (typeof this.dfds[i] === 'function') {
this.dfds[i]();
} else {
this.dfds[i].r = true; //ready
if (this.dfds[i].s === 0) { //not ready yet so we can't continue
break; //todo: if we don't want to maintain order in a level then make this continue or something
}
this.dfds[i].g.complete(normalizedState);
}
this.dfds.splice(i, 1);
i--;
}
//if there are any dfds left, don't complete this level
if (this.dfds.length > 0) {
return;
}
//if we're rejected then we cannot continue and call the next level, instead just call failCallbacks
if (this.state === 'rejected') {
this.completeFailed(originalArgs);
return;
}
this.cleanup();
if (this.nextLevel !== null) {
this.nextLevel.ready = true;
this.nextLevel.complete(originalArgs);
}
this.cleanupLevelRefs();
};
LevelContainer.prototype.completeFailed = function(originalArgs) {
this.failedArgs = this.failedArgs || originalArgs;
callFuncsOptimized(this.failCallbacks, this.failedArgs, this.chain);
this.failCallbacks.splice(0, this.failCallbacks.length);
this.cleanup();
if (this.nextLevel !== null) {
this.nextLevel.completeFailed(this.failedArgs);
}
this.cleanupLevelRefs();
};
LevelContainer.prototype.cleanup = function(cleanupNext) {
var i, l;
for (i = 0, l = this.dfds.length; i < l; i++) {
this.dfds[i].r = false; //not ready
}
this.dfds.splice(0, this.dfds.length);
this.completed = true;
//just empty the array
this.failCallbacks.splice(0, this.failCallbacks.length);
};
LevelContainer.prototype.cleanupLevelRefs = function() {
this.nextLevel = null;
if (this.prevLevel !== null) {
//we don't need to keep around the args in previous levels since addFailCallback is only called for newest level
this.prevLevel.failedArgs = null;
this.prevLevel = null;
}
};
LevelContainer.prototype.normalizedState = function() {
//if the state is 'stopped' then it should actually be 'rejected'
if (this.state === 'stopped') {
return 'rejected';
}
if (this.state === 'ignored') {
return 'resolved';
}
//state is '' when its pending
return this.state || 'pending';
};
LevelContainer.prototype.stop = function(cleanupNext) {
//don't let this complete
this.ready = false;
this.state = 'stopped';
this.cleanup();
if (this.nextLevel !== null) {
this.nextLevel.stop();
}
this.cleanupLevelRefs();
};
//todo: remove globalCallbacks and completedDeferreds
function GroupedDfd(deferreds, onComplete, globalCallbacks, completedDeferreds) {
this.args = [];
this.promise = new GroupedDfdPromise();
var resp = this,
promise = this.promise,
allDfds = [],
complete = false,
canResolve = false;
function callOnComplete(state) {
if (complete) {
return;
}
complete = true;
//make sure allDfds is empty
allDfds.length = 0;
onComplete(state, resp, resp.args);
}
function onResolve() {
//loop through the deferreds and build the response args array in order
//we must wait until canResolve is true otherwise we're still looping through allDfds so we can't splice
for (var i = 0; i < allDfds.length && canResolve && !complete; i++) {
//once we hit one that isn't resolved then break
if (allDfds[i].s === 0) {
break;
}
if (allDfds[i].args !== null) {
resp.args.push.apply(resp.args, allDfds[i].args);
}
allDfds.splice(i, 1);
i--;
}
if (allDfds.length === 0) {
callOnComplete('resolved');
}
}
//create the objects that hold each deferred, its state and the args it returned
var i, l;
for (i = 0, l = deferreds.length; i < l; i++) {
if (deferreds[i] === undefined) {
throw new Error('Undefined sent to push/add. Did you forget to return a deferred?');
}
//s of 0 means not done and s of 1 means done
allDfds.push({d: deferreds[i], s: 0, args: null});
}
//we need to loop a second time since a deferred could IMMEDATELY resolve
for (i = 0, l = allDfds.length; i < l && !complete; i++) {
//FIRST check for .then since "deferred" returns a "function" for promise
if (typeof allDfds[i].d.then !== 'function') {
if (typeof allDfds[i].d === 'function') {
allDfds[i].s = 1;
this.promise.done(allDfds[i].d);
continue;
}
throw new Error('Invalid deferred sent to chain');
}
//add handlers to the deferred so we can store the state it resolved as and the args it returned
(function(obj) {
obj.d.then(function() {
if (obj.s !== 0) {
return;
}
obj.args = slice.call(arguments);
obj.s = 1;
var dfd = this;
promise.done(function() {
completedDeferreds.set(dfd);
//temporary for backwards-compat
for (var j = 0; j < globalCallbacks.length; j++) {
if (dfd === globalCallbacks[j].d) {
promise.done(globalCallbacks[j].func);
globalCallbacks.splice(j, 1);
j--;
}
}
});
onResolve();
}, function() {
if (obj.s !== 0) {
return;
}
//overwrite the args on the response since we failed, we want the failed stuff to get called with the failed args
resp.args = slice.call(arguments);
obj.s = 1;
var dfd = this;
promise.fail(function() {
completedDeferreds.set(dfd);
//temporary for backwards-compat
for (var j = 0; j < globalCallbacks.length; j++) {
if (dfd === globalCallbacks[j].d) {
promise.fail(globalCallbacks[j].func);
globalCallbacks.splice(j, 1);
j--;
}
}
});
//if we failed, we can immediately stop and bail
callOnComplete('rejected');
});
}(allDfds[i]));
}
//start allowing resolving now
canResolve = true;
//if there was only functions or deferreds already resolved, immediately resolve (only if we didn't already resolve)
//a resolve might've be called but we had to postpone till we were done looping
onResolve();
}
GroupedDfd.prototype.complete = function(s) {
var callbacks = this.promise.callbacks,
callbackFuncs = [],
i;
//set state first so that if someone calls group.done inside of a done callback it'll get handled immediately
if (this.promise.s !== 'pending') {
return;
}
this.promise.args = this.args;
this.promise.s = s;
if (callbacks === null) {
return;
}
for (i = 0; i < callbacks.length; i++) {
if (callbacks[i].s === this.promise.s) {
callbackFuncs.push(callbacks[i].f);
}
}
//we don't need this array anymore
this.promise.callbacks = null;
callFuncsOptimized(callbackFuncs, this.promise.args, this.promise.ctx);
};
function GroupedDfdPromise(context) {
this.ctx = context || this;
this.s = 'pending';
this.args = null;
this.callbacks = null;
}
GroupedDfdPromise.prototype.done = function() {
var i, l;
if (this.s === 'resolved') {
callFuncsOptimized(slice.call(arguments), this.args, this.ctx);
} else if (this.s === 'pending') {
for (i = 0, l = arguments.length; i < l; i++) {
if (typeof arguments[i] !== 'function') {
throw new Error('Invalid function sent to done ' + (typeof arguments[i]));
}
if (this.callbacks === null) {
this.callbacks = [];
}
this.callbacks.push({s: 'resolved', f: arguments[i]});
}
} //else its already rejected
return this;
};
GroupedDfdPromise.prototype.then = function(doneCallbacks, failCallbacks) {
if (typeof doneCallbacks === 'function') {
this.done(doneCallbacks);
} else if (doneCallbacks instanceof Array) {
this.done.apply(this, doneCallbacks);
}
if (typeof failCallbacks === 'function') {
this.fail(failCallbacks);
} else if (failCallbacks instanceof Array) {
this.fail.apply(this, failCallbacks);
}
return this;
};
GroupedDfdPromise.prototype.fail = function() {
var i, l;
if (this.s === 'rejected') {
callFuncsOptimized(slice.call(arguments), this.args, this.ctx);
} else if (this.s === 'pending') {
for (i = 0, l = arguments.length; i < l; i++) {
if (typeof arguments[i] !== 'function') {
throw new Error('Invalid function sent to fail ' + (typeof arguments[i]));
}
if (this.callbacks === null) {
this.callbacks = [];
}
this.callbacks.push({s: 'rejected', f: arguments[i]});
}
} //else its already resolved
return this;
};
GroupedDfdPromise.prototype['catch'] = GroupedDfdPromise.prototype.fail;
GroupedDfdPromise.prototype.always = function() {
var args = slice.call(arguments);
return this.fail.apply(this, args).done.apply(this, args);
};
//todo: implement other dfd methods
GroupedDfdPromise.prototype.state = function() {
return this.s;
};
//an empty promise will never be resolved
function EmptyPromise() {}
for (var m in GroupedDfdPromise.prototype) {
if (GroupedDfdPromise.prototype.hasOwnProperty(m) && typeof GroupedDfdPromise.prototype[m] === 'function') {
EmptyPromise.prototype[m] = noopThis;
}
}
//state is a special case
EmptyPromise.prototype.state = function() {
return 'pending';
};
function ChainLoading() {
var self = this,
deferredCallbacks = [],
completedDeferreds = new CompletedMap(), //deferreds that have completed, used for binds that happened after a push/add
globalFailCallbacks,
storedArgs, currentLevel,
promise;
function levelFailed() {
if (globalFailCallbacks === undefined) {
return;
}
for (var i = 0; i < globalFailCallbacks.length; i++) {
globalFailCallbacks[i].call(self);
globalFailCallbacks.splice(i, 1);
i--;
}
}
function newLevel() {
var hasCurrentLevel = currentLevel !== undefined,
level = new LevelContainer(self, (!hasCurrentLevel || currentLevel.completed));
if (globalFailCallbacks !== undefined) {
level.addFailCallback(levelFailed);
}
if (hasCurrentLevel) {
currentLevel.nextLevel = level;
level.prevLevel = currentLevel;
//we only need to have the levelFailed on the LAST level, we don't need it on all the levels in between
currentLevel.removeFailCallback(levelFailed);
}
currentLevel = level; //advance level
return level;
}
/**
* Exposed methods
*/
function push(func, args) {
//if we've already failed then just short-circuit
if (currentLevel !== undefined && currentLevel.normalizedState() === 'rejected') {
return new EmptyPromise();
}
newLevel();
return currentLevel[func](args, deferredCallbacks, completedDeferreds);
}
function add(func, args) {
if (currentLevel === undefined) {
newLevel();
} else if (currentLevel.normalizedState() === 'rejected') {
return new EmptyPromise();
}
return currentLevel[func](args, deferredCallbacks, completedDeferreds);
}
//adds deferreds/functions to the next level
this.push = this.next = function() {
//each argument is a deferred or function
return push('requireDeferreds', slice.call(arguments));
};
//adds deferreds to the same level and doesn't increase it (useful for parallel operations where return order doens't matter)
this.add = function() {
//each argument is a deferred or function
return add('requireDeferreds', slice.call(arguments));
};
//adds deferreds to the next level (index)
//if any of the deferreds fail it'll keep going through the levels
this.pushIgnoreFail = this.nextIgnoreFail = function() {
return push('optionalDeferreds', slice.call(arguments));
};
//adds deferreds to the same level and doesn't increase it (useful for parallel operations where return order doens't matter)
//if any of the deferreds fail it'll keep going through the levels
this.addIgnoreFail = function() {
//each argument is a deferred or function
return add('optionalDeferreds', slice.call(arguments));
};
this.stop = function() {
var levelToStop = currentLevel;
if (levelToStop === undefined) {
levelToStop = newLevel();
} else {
//find the first level that we still have around
while (levelToStop.prevLevel !== null && (levelToStop = levelToStop.prevLevel)) {}
}
levelToStop.stop();
return this;
};
this.fail = this['catch'] = function(func) {
if (currentLevel === undefined) {
//todo: if there's a better way to do this, that'd be awesome
if (globalFailCallbacks === undefined) {
globalFailCallbacks = [];
}
globalFailCallbacks.push(func);
} else {
currentLevel.addFailCallback(func);
}
return this;
};
var internalBind = function(func, context, curried) {
return function() {
var f;
//building function all the time so we don't duplicate code (only 5-10% slower http://jsperf.com/concat-vs-length)
if (curried === undefined) { //can't just check curried.length since it might be storedArgs which gets larger later
f = function() {
func.apply(context, slice.call(arguments));
};
} else {
f = function() {
func.apply(context, curried.concat(slice.call(arguments)));
//easy way of emptying array (from: http://stackoverflow.com/questions/1232040/how-to-empty-an-array-in-javascript/1234337#1234337)
curried.length = 0;
};
}
//this is the actual deferred unless someone did chain.done(chain.bind(...))
if (this === self || (this instanceof GroupedDfdPromise) || completedDeferreds.has(this)) {
f.apply(this, slice.call(arguments));
} else {
if (typeof this.state !== 'function') {
throw new Error('You tried to use chain.bind with an unsupported deferred library. See README.md and stop using chain.bind');
}
deferredCallbacks.push({d: this, func: f, s: this.state()});
}
};
};
//emulate bind but we need the context from the deferred. This is REQUIRED for each deferred's callbacks
this.bind = function(func, context) {
if (arguments.length < 3) {
return internalBind(func, context);
} else {
return internalBind(func, context, slice.call(arguments, 2));
}
};
//this is basically bind but will apply the storedArgs as if they were curried
this.applyArgs = function(func, context) {
if (arguments.length < 3) { //optimize for usual case
//make sure stored args isn't null so we can pass a reference to internalBind
if (storedArgs === undefined) storedArgs = [];
return internalBind(func, context, storedArgs);
} else {
var curried = slice.call(arguments, 2);
return function() {
//this is also clearing out storedArgs, unless its undefined which means that storeArgs was never called?
var args = (storedArgs || []).splice(0, storedArgs.length).concat(curried).concat(slice.call(arguments));
internalBind(func, context, args).call(this);
};
}
};
this.storeArgs = function() {
//this is the actual deferred unless someone did chain.done(chain.storeArgs(...))
var args = slice.call(arguments),
storeArgs = function() {
//if storedArgs is null then they either haven't called applyArgs or they passed >3 arguments
if (storedArgs === undefined) storedArgs = [];
//cannot use concat on storedArgs since we need ref to be the same for internalBind to work correctly
storedArgs.push.apply(storedArgs, args);
};
if (this === self) {
//if they did chain.push(chain.storeArgs(stuff)) we want to just put that into the chain and it call it when ready
return storeArgs;
} else if ((this instanceof GroupedDfdPromise) || completedDeferreds.has(this)) {
//if a grouped promise was completed or if the deferred was already completed
storeArgs();
} else {
deferredCallbacks.push({d: this, func: storeArgs, s: this.state()});
}
};
this.state = function() {
if (currentLevel === undefined) {
return 'pending';
}
return currentLevel.normalizedState();
};
this.promise = function() {
if (promise === undefined) {
var tinyBind = function(func, context) {
//right now all the things we're binding below require less than 3 args
return function(oneArg, twoArg, threeArg) {
return func.call(context, oneArg, twoArg, threeArg);
};
};
promise = {
state: this.state, //no bind needed
done: tinyBind(this.done, this),
fail: tinyBind(this.fail, this),
always: tinyBind(this.always, this),
then: tinyBind(this.then, this)
};
}
return promise;
};
}
ChainLoading.prototype.done = ChainLoading.prototype.after = function(func, runAtCurrent) {
if (runAtCurrent) {
this.add(func);
} else {
this.push(func);
}
return this;
};
ChainLoading.prototype.then = function(doneCallbacks, failCallbacks) {
var i, l;
if (typeof doneCallbacks === 'function') {
this.done(doneCallbacks);
} else if (doneCallbacks instanceof Array) {
for (i = 0, l = doneCallbacks.length; i < l; i++) {
this.done(doneCallbacks[i]);
}
}
if (typeof failCallbacks === 'function') {
this.fail(failCallbacks);
} else if (failCallbacks instanceof Array) {
for (i = 0, l = failCallbacks.length; i < l; i++) {
this.fail(failCallbacks[i]);
}
}
return this;
};
ChainLoading.prototype.always = function(func) {
//fast-case
if (arguments.length === 1) {
return this.fail(func).done(func);
}
var funcs = slice.call(arguments);
return this.fail.apply(this, funcs).done.apply(this, funcs);
};
//makes a new chain that's initially based off the of the current level of this chain
ChainLoading.prototype.fork = function() {
var newChain = new ChainLoading();
newChain.push(this);
return newChain;
};
if (typeof module !== "undefined") {
module.exports = ChainLoading;
} else {
window.ChainLoading = ChainLoading;
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
define('ChainLoading', function() { return ChainLoading; });
}
}
}(this));