Skip to content

Instantly share code, notes, and snippets.

@nanxiaobei
Created October 29, 2021 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanxiaobei/9c7b065c73927bff5958c2bc635fb935 to your computer and use it in GitHub Desktop.
Save nanxiaobei/9c7b065c73927bff5958c2bc635fb935 to your computer and use it in GitHub Desktop.
MyPromise
class MyPromise {
constructor(fn) {
this.status = 'PENDING';
const resolve = (data) => {
if (this.status !== 'PENDING') return;
this.status = 'FULLFILLED';
this.value = data;
this.onChange?.();
};
const reject = (data) => {
if (this.status !== 'PENDING') return;
this.status = 'REJECTED';
this.value = data;
this.onChange?.();
};
try {
fn(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onResolve, onReject) {
return new MyPromise((resolve, reject) => {
const map = { FULLFILLED: [onResolve, resolve], REJECTED: [onReject, reject] };
const onChange = () => {
setTimeout(() => {
const [callback, fallback] = map[this.status];
if (typeof callback !== 'function') {
fallback(this.value);
return;
}
try {
const result = callback(this.value);
result instanceof MyPromise ? result.then(resolve) : resolve(result);
} catch (err) {
reject(err);
}
});
};
if (this.status === 'PENDING') {
this.onChange = onChange;
} else {
onChange();
}
});
}
catch(onReject) {
return this.then(null, onReject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment