Skip to content

Instantly share code, notes, and snippets.

@isavch
Last active December 19, 2017 15:17
Show Gist options
  • Select an option

  • Save isavch/4ad8190b50d72e40821c0087eef92b42 to your computer and use it in GitHub Desktop.

Select an option

Save isavch/4ad8190b50d72e40821c0087eef92b42 to your computer and use it in GitHub Desktop.
promise
class MyPromise {
constructor(handler) {
this.status = 'pending';
if (!handler) {
throw new TypeError('Promise resolver is undefined');
}
handler(value => {
this.value = value;
}, error => {
this.value = error;
})
}
then(succCb, errorCb) {
try {
this.value = succCb(this.value);
this.status = 'resolved';
} catch(error) {
this.status = 'rejected';
if(errorCb) {
this.value = errorCb(error);
} else {
this.value = error;
}
return this;
}
return this;
}
catch(errorCb) {
if (errorCb && this.status === 'rejected') {
this.value = errorCb(this.value);
}
return this
}
}
var a = new MyPromise((resolve, reject) => {
resolve(1);
});
a.then(s => {
console.log(s);
return 4;
})
.then(d => {
console.log(d);
throw 3;
})
.catch(e => {
console.log(e, 'catch');
return 5;
}).then(p => console.log(p));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment