Skip to content

Instantly share code, notes, and snippets.

@lyuehh
Created February 26, 2013 13:01
Show Gist options
  • Save lyuehh/5038247 to your computer and use it in GitHub Desktop.
Save lyuehh/5038247 to your computer and use it in GitHub Desktop.
/*
from http://www.cnblogs.com/iamzhanglei/archive/2013/02/24/2924680.html
*/
var Promise = function() {
this.thens = [];
};
Promise.prototype = {
resolve: function() {
var t = this.thens.shift(), n;
n = t.apply(null, arguments); // n instanceof Promise && (n.thens = this.thens));
if(n instanceof Promise) {
n.thens = this.thens;
}
},
then: function(n) {
this.thens.push(n);
return this;
}
};
function f1() {
var promise = new Promise();
setTimeout(function() {
console.log(1);
promise.resolve();
}, 1000);
return promise;
}
function f2() {
var promise = new Promise();
setTimeout(function() {
console.log(2);
promise.resolve();
}, 1000);
return promise;
}
function f3() {
var promise = new Promise();
setTimeout(function() {
console.log(3);
promise.resolve();
}, 1000);
return promise;
}
function f4() {
console.log(4);
}
f1().then(f2).then(f3).then(f4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment