feat: 重新按另外一种思路实现的手写Promise
This commit is contained in:
parent
eee04539d8
commit
8ab54e7d59
69
js/修正版promise.js
Normal file
69
js/修正版promise.js
Normal file
@ -0,0 +1,69 @@
|
||||
// Promise 状态常量
|
||||
MyPromise.PENDING = 0
|
||||
MyPromise.FULFILLED = 1
|
||||
MyPromise.REJECT = 2
|
||||
|
||||
function MyPromise(fun){
|
||||
this.status = MyPromise.PENDDING
|
||||
this.result = undefined
|
||||
try {
|
||||
fun(MyPromise.resolve.bind(this), MyPromise.reject.bind(this))
|
||||
} catch (error) {
|
||||
MyPromise.reject.call(this, error)
|
||||
}
|
||||
}
|
||||
|
||||
MyPromise.resolve = function(res){ // 在这里会拿到构造函数传过来的确认值
|
||||
this.status = MyPromise.FULFILLED
|
||||
this.result = res
|
||||
var context = this
|
||||
setTimeout(function(){
|
||||
try {
|
||||
if(typeof context.$onFulfilled === 'function') {
|
||||
var nextResult = context.$onFulfilled(context.result) // then里面回调返回的值,如果后面继续调用了then,那么就传给它
|
||||
}
|
||||
// 如果有nextMyPromise,说明调用者继续调用了then,如果then注册了onfulfilled那么久吧返回值给它
|
||||
if (context.nextMyPromise) {
|
||||
MyPromise.resolve.call(context.nextMyPromise, typeof context.$onFulfilled === 'function' ? nextResult : context.result)
|
||||
}
|
||||
}catch(err){
|
||||
if(context.nextMyPromise) {
|
||||
MyPromise.reject.call(context.nextMyPromise, err)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MyPromise.reject = function (err) { // 在这里会拿到构造函数传过来的拒绝值
|
||||
this.status = MyPromise.REJECT
|
||||
this.result = err
|
||||
var context = this
|
||||
setTimeout(function(){
|
||||
try{
|
||||
if(typeof context.$onReject === 'function') {
|
||||
var nextResult = context.$onReject(context.result) // then里面回调返回的值,如果后面继续调用了then,那么就传给它
|
||||
}
|
||||
// 如果有nextMyPromise,说明调用者继续调用了then,如果then注册了onfulfilled那么久吧返回值给它
|
||||
if (context.nextMyPromise && typeof context.$onReject === 'function') {
|
||||
MyPromise.resolve.call(context.nextMyPromise, nextResult) // 已经进行了异常处理,把返回值交给下一个onFulfilled
|
||||
}
|
||||
if (context.nextMyPromise && context.$onReject === undefined) {
|
||||
MyPromise.reject.call(context.nextMyPromise, context.result) // 没有进行错误处理,交给下一个onReject处理
|
||||
}
|
||||
if (!context.nextMyPromise && context.$onReject === undefined) {
|
||||
console.error(context.result) // 没有下一个then,并且当前也没处理,直接打印错误到控制台
|
||||
}
|
||||
} catch (err){ // 当then中的onReject出现异常时,我们应该检查是否有下一个then,有的话就调用
|
||||
if(context.nextMyPromise) MyPromise.reject.call(context.nextMyPromise, err)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MyPromise.prototype.then = function (onFulfilled, onReject) {
|
||||
// 把传过来的两个回调函数先保存起来,因为resolve可能会被异步调用,会在then后面执行
|
||||
this.$onFulfilled = onFulfilled
|
||||
this.$onReject = onReject
|
||||
// 创建一个MyPromise,并且返回实现链式调用
|
||||
this.nextMyPromise = new MyPromise((resolve,reject)=>{})
|
||||
return this.nextMyPromise
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user