function MyPromise(exctor) {
this.state = 'pending';
this.fillFulledResult = ''
this.rejectReason = ''
this.fullfilledList = []
this.rejectList = []
const reslove = (value) => {
if (this.state == 'pending') {
this.state = 'fullfilled'
this.fillFulledResult = value
this.fullfilledList.forEach((fn) => {
fn(value)
})
}
}
const reject = (value) => {
if (this.state == 'pending') {
this.state = 'rejected'
this.rejectReason = value
this.rejectList.forEach((fn) => {
fn(value)
})
}
}
exctor(reslove, reject)
}
// promise是链式调用的,所以在then 方法里返回的是一个promise对象
MyPromise.prototype.then = function (onFullfilled, onReject) {
let that = this;
return new MyPromise((reslove, reject) => {
switch (that.state) {
case 'pending':
that.fullfilledList.push(value => {
setTimeout(() => {
try {
const result = onFullfilled(value);
reslovePromiseHandle(result)
} catch (error) {
reject(error)
}
}, 0);
})
that.rejectList.push(value => {
setTimeout(() => {
try {
const result = onReject(value);
reslovePromiseHandle(result)
} catch (error) {
reject(error)
}
}, 0);
})
break
case 'fullfilled':
setTimeout(() => {
try {
const success = onFullfilled(that.fillFulledResult);
reslovePromiseHandle(success)
} catch (error) {
reject(error)
}
}, 0);
break
case 'rejected':
setTimeout(() => {
try {
const errorreason = onReject(that.rejectReason);
reslovePromiseHandle(errorreason)
} catch (error) {
reject(error)
}
}, 0);
break
}
function reslovePromiseHandle (result) {
if (result instanceof MyPromise) {
result.then(reslovePromiseHandle, reject)
return
}
reslove(result)
}
})
}
MyPromise.prototype.catch = function (onReject) {
return this.then(null , onReject)
}
new MyPromise((reslove, reject) => {
reslove(2)
}).then(res => {
console.log('+++',res)
return res +'1111'
}).then(res => new MyPromise((reslove, reject) => {
console.log(res +'1111')
reject('error' + res)
})).catch(error => {
console.log(error)
return 'jhhhh'
}).then(res => {
console.log(res +'1111+catch')
})
//+++ 2
//211111111
//error21111
//jhhhh1111+catch
手写 promise
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- promise promise.all promise.allSettled promise.race
- Promise概念 Promise是异步编程的一种解决方案,将异步操作以同步的流程表达出来,避免了层层嵌套的回调函...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/565ad78b4b3b] ),继续...
- promise的术语 promise 是一个有then方法的对象或者是函数,行为遵循本规范 thenable 是一...
- 咱们书接上文( 点我查看[https://www.jianshu.com/p/5a03197461d8] ),继续...