Created
March 3, 2020 01:18
-
-
Save fengkx/022beb48b1aed50cd957aad07abe9edb to your computer and use it in GitHub Desktop.
Promise
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
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