Skip to content

Instantly share code, notes, and snippets.

@fengkx
Created March 3, 2020 01: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 fengkx/022beb48b1aed50cd957aad07abe9edb to your computer and use it in GitHub Desktop.
Save fengkx/022beb48b1aed50cd957aad07abe9edb to your computer and use it in GitHub Desktop.
Promise
const PENDING = Symbol('pending');
const FULFILLED = Symbol('fulfilled');
const REJECTED = Symbol('rejected');
class MyPromise {
constructor(excutor) {
this.state = PENDING;
this.value = undefined;
this.err = undefined;
this.onFulfill = [];
this.onReject = [];
const resolve = (value) => {
if(this.state === PENDING) {
this.value = value;
this.state = FULFILLED;
this.onFulfill.map(fn => fn(value));
}
};
const reject = (err) => {
if(this.state === PENDING) {
this.state = REJECTED;
this.err = err;
this.onReject.map(fn => fn(err));
}
};
try {
excutor(resolve, reject)
} catch (err) {
reject(err)
}
}
then(onFulfilled = () => {}, onReject = () => {}) {
// console.log(this.state)
switch(this.state) {
case FULFILLED:
onFulfilled(this.value);
break;
case REJECTED:
onReject(this.err);
break;
case PENDING:
this.onFulfill.push(onFulfilled);
this.onReject.push(onReject);
}
}
}
function timeoutPromise(ms) {
return new MyPromise((resolve, reject) => {
setTimeout(function() {
resolve(123);
}, ms)
});
}
const p = timeoutPromise(3000);
p.then((value) => {
console.log('time out 3000')
console.log(value)
}, (err) => {
console.log(err)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment