Created
October 17, 2013 09:04
-
-
Save zserge/7021626 to your computer and use it in GitHub Desktop.
Extemely minimalistic implementation of promises/futures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function chain(callback) { | |
var queue = []; | |
function _next() { | |
var cb = queue.shift(); | |
if (cb) { | |
cb(_next); | |
} | |
} | |
setTimeout(_next, 0); | |
var then = function(cb) { | |
queue.push(cb); | |
return { then: then } | |
} | |
return then(callback); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//137 bytes | |
function chain(a){function c(){var a=b.shift();a&&a(c)}var b=[];setTimeout(c,0);var d=function(a){return b.push(a),{then:d}};return d(a)} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
chain(function(next) { | |
console.log('1'); | |
setTimeout(function() { | |
console.log('2'); | |
next(); | |
}, 1000); | |
}).then(function(next) { | |
console.log('3'); | |
setTimeout(function() { | |
console.log('4'); | |
next(); | |
}, 1000); | |
}).then(function(next) { | |
console.log('5'); | |
next(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment