Created
October 29, 2017 05:02
-
-
Save coderek/0880e2912eb478415d80d7434e0d05d1 to your computer and use it in GitHub Desktop.
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(task) { | |
this._state = 'init'; | |
this._resolve_handler = null; | |
this._reject_handler = null; | |
this._resolved_value = null; | |
this._rejected_value = null; | |
this._resolve = this._resolve.bind(this); | |
this._reject = this._reject.bind(this); | |
task(this._resolve, this._reject); | |
return this; | |
} | |
MyPromise.resolved = function (val) { | |
const p = new MyPromise(res=>res(val)); | |
p._state = 'resolved'; | |
return p; | |
} | |
MyPromise.prototype = { | |
_resolve: function(val) { | |
this._state = 'resolved'; | |
this._resolved_value = val; | |
if (this._resolve_handler) { | |
this._resolve_handler(val); | |
} | |
}, | |
_reject: function(err) { | |
this._state = 'rejected'; | |
this._rejected_value = err; | |
if (this._reject_handler) { | |
this._reject_handler(err); | |
} | |
}, | |
then: function(resolved, rejected) { | |
return new MyPromise((res, rej)=> { | |
if (this._state === 'init') { | |
this._resolve_handler = function (val) { | |
res(resolved(val)); | |
}; | |
this._reject_handler = function (err) { | |
res(rejected(err)); | |
} | |
} else if (this._state === 'resolved') { | |
res(resolved(this._resolved_value)); | |
} else if (this._state === 'rejected') { | |
res(rejected(this._rejected_value)); | |
} | |
}); | |
} | |
} | |
p = new MyPromise((res, rej)=> { | |
setTimeout(()=> { | |
rej('hello') | |
}) | |
}); | |
p.then(val => { | |
console.log('console.log('+val+')'); | |
return 123; | |
}, err=> console.log(err)).then(console.log) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment