From 8ab54e7d59e18040fcd9543d211e0448db0e206b Mon Sep 17 00:00:00 2001 From: yigencong Date: Sat, 13 Apr 2024 20:48:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=87=8D=E6=96=B0=E6=8C=89=E5=8F=A6?= =?UTF-8?q?=E5=A4=96=E4=B8=80=E7=A7=8D=E6=80=9D=E8=B7=AF=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E7=9A=84=E6=89=8B=E5=86=99Promise?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/修正版promise.js | 69 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 js/修正版promise.js diff --git a/js/修正版promise.js b/js/修正版promise.js new file mode 100644 index 0000000..20e9134 --- /dev/null +++ b/js/修正版promise.js @@ -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 +}