Utilities
Asynchronous
function Chain(){ this.links = []; } Chain.prototype.link = function link(cb){ this.links.push(cb); return this; } Chain.prototype.run = function run(end){ var self = this; var next = function(i){ return function(){ if (i < self.links.length){ self.links[i](next(i+1), end); // i++ makes it harder to reason about this line } else { end() // <-- end will not be called unless the chain is explicitly ended in a link } } }; next(0)(); }
- function Chain(){
- this.links = [];
- }
- Chain.prototype.link = function link(cb){
- this.links.push(cb);
- return this;
- }
- Chain.prototype.run = function run(end){
- var self = this;
- var next = function(i){
- return function(){
- if (i < self.links.length){
self.links[i++](next(i), end);- self.links[i](next(i+1), end); // i++ makes it harder to reason about this line
- } else {
- end() // <-- end will not be called unless the chain is explicitly ended in a link
- }
- }
- };
- next(0)();
- }
var countAndNext = function(next, end){ i++; next(); }; var countAndEnd = function(next, end){ i++; end(); }; var i = 0; new Chain().link(countAndNext).link(countAndEnd).link(function(next, end){ Test.fail('Should not run'); }).run(function(){ Test.assertEquals(i, 2); }); i = 0; new Chain().link(countAndNext).link(countAndNext).link(countAndNext).run(function(){ Test.assertEquals(i, 3); });
var chain = new Chain();var i = 0;chain.link(function(next, end){- var countAndNext = function(next, end){
- i++;
- next();
});- };
chain.link(function(next, end){- var countAndEnd = function(next, end){
- i++;
- end();
- };
- var i = 0;
- new Chain().link(countAndNext).link(countAndEnd).link(function(next, end){
- Test.fail('Should not run');
- }).run(function(){
- Test.assertEquals(i, 2);
- });
chain.link(function(next, end){i++;console.log('Should not have ran');- i = 0;
- new Chain().link(countAndNext).link(countAndNext).link(countAndNext).run(function(){
- Test.assertEquals(i, 3);
- });
chain.run(function(){Test.assertEquals(i, 2);});