Skip to content

Instantly share code, notes, and snippets.

@coderek
Created October 29, 2017 05:02
Show Gist options
  • Save coderek/0880e2912eb478415d80d7434e0d05d1 to your computer and use it in GitHub Desktop.
Save coderek/0880e2912eb478415d80d7434e0d05d1 to your computer and use it in GitHub Desktop.
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