Created
May 16, 2018 13:53
-
-
Save licaomeng/528d0a63c3305531c5b36c138fea17dc to your computer and use it in GitHub Desktop.
JavaScript-Promise-Lite
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 MyPromise(fn) { | |
this.resolve; | |
this.reject; | |
_this = this; | |
setTimeout(function () { | |
fn(_this.resolveFunc.bind(_this), _this.rejectFunc.bind(_this)); | |
}, 0) | |
} | |
MyPromise.prototype = { | |
then: function (resolve, reject) { | |
this.resolve = resolve; | |
this.reject = reject; | |
}, | |
resolveFunc: function (value) { | |
this.resolve(value); | |
}, | |
rejectFunc: function (value) { | |
this.reject(value); | |
} | |
} | |
new MyPromise(function (resolve, reject) { | |
var flag = Math.round(Math.random()) | |
if (flag) { | |
resolve(flag); | |
} else { | |
reject(flag); | |
} | |
}).then(function (resolve) { | |
console.log(resolve); | |
}, function (reject) { | |
console.log(reject); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment