Skip to content

Instantly share code, notes, and snippets.

@zserge
Created October 17, 2013 09:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zserge/7021626 to your computer and use it in GitHub Desktop.
Save zserge/7021626 to your computer and use it in GitHub Desktop.
Extemely minimalistic implementation of promises/futures
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);
}
//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)}
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