js-review/js/修正版promise.js

70 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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
}