const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
class MyPromise {
constructor(fn) {
this.state = PENDING
this.value = null
this.resolveCallback = []
this.rejectCallback = []
const resolve = value => {
if (this.state === PENDING) {
this.state = RESOLVED
this.value = value
this.resolveCallback.map(cb => cb(value))
}
}
const reject = value => {
if (this.state === PENDING) {
this.state = REJECTED
this.value = value
this.rejectCallback.map(cb => cb(value))
}
}
try {
fn(resolve, reject)
} catch (ex) {
reject(ex)
}
}
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : t => {throw(t)}
if (this.state === PENDING) {
this.resolveCallback.push(onFulfilled)
this.rejectCallback.push(onRejected)
}
if (this.state === RESOLVED) {
onFulfilled(this.value)
}
if (this.state === REJECTED) {
onRejected(this.value)
}
}
}
const sleep = timer => new MyPromise((resolve,reject) => setTimeout(resolve, timer))
async function AsyncF() {
for (let i=1;i<=10;i++) {
await sleep(2000)
console.log(i)
}
}
AsyncF()
console