Last active
December 10, 2015 08:30
-
-
Save shuding/c36a24b31bc894ea0045 to your computer and use it in GitHub Desktop.
Promise
This file contains 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 a (callback) { | |
setTimeout(function () { | |
console.log('This is a'); | |
callback && callback(null); | |
}, 100); | |
} | |
function b (callback) { | |
setTimeout(function () { | |
console.log('This is b'); | |
callback && callback(); | |
}, 200); | |
} | |
function c (callback) { | |
setTimeout(function () { | |
console.log('This is c'); | |
callback && callback(); | |
}, 10); | |
} | |
function d (callback) { | |
setTimeout(function () { | |
console.log('This is d'); | |
callback && callback(); | |
}, 60); | |
} | |
//a(); b(); c(); d(): | |
// a(function () { | |
// b(function () { | |
// c(function () { | |
// d(); | |
// }); | |
// }); | |
// }); | |
function promise() { | |
if (!(this instanceof promise)) { | |
var pr = new promise(); | |
pr.resolve_set = true; | |
return pr; | |
} | |
this.resolve_set = false; | |
this.resolve_fn = null; | |
this.__check = function () { | |
if (this.resolve_set && this.resolve_fn) { | |
this.resolve_fn.exec(); | |
} | |
} | |
} | |
promise.prototype.resolve = function () { | |
this.resolve_set = true; | |
this.__check(); | |
} | |
promise.prototype.then = function (fn) { | |
this.resolve_fn = fn.promise(); | |
this.__check(); | |
return this.resolve_fn.promise; | |
} | |
function promise_obj (fn) { | |
this.promise = new promise(); | |
this.fn = fn; | |
} | |
promise_obj.prototype.exec = function () { | |
var self = this; | |
this.fn(function () { | |
self.promise.resolve(); | |
}); | |
}; | |
function promisify (fn) { | |
var ret = function () { | |
fn.apply(this, arguments); | |
}; | |
ret.promise = function () { | |
return new promise_obj(fn); | |
} | |
return ret; | |
} | |
var _a = promisify(a); | |
var _b = promisify(b); | |
var _c = promisify(c); | |
var _d = promisify(d); | |
var pr = promise().then(_a).then(_b).then(_c); | |
_d(); | |
_c(); | |
_c(function () { | |
_a(); | |
}); | |
pr.then(_d).then(_a).then(_d); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment