From eee04539d853629b8aa97492ec07c3eade8905c4 Mon Sep 17 00:00:00 2001 From: yigencong Date: Mon, 8 Apr 2024 18:34:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E9=9D=99=E6=80=81?= =?UTF-8?q?=E5=87=BD=E6=95=B0reslove=E5=92=8Creject=E4=BB=A5=E5=8F=8Aall?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/手写Promise.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/js/手写Promise.js b/js/手写Promise.js index 98b12d4..bb9e43f 100644 --- a/js/手写Promise.js +++ b/js/手写Promise.js @@ -19,12 +19,14 @@ MyPromise.REJECT = 2 MyPromise.resolve = function(res) { + if(this === MyPromise) return new MyPromise(resolve=>resolve(res)) // 如果是静态调用就返回一个确认的Promise if(this.status === MyPromise.REJECT) return // Promise 的状态一旦确定就不能修改 this.status = MyPromise.FULFILLED this.result = res } MyPromise.reject = function(err) { + if(this === MyPromise) return new MyPromise((resolve,reject)=>reject(err)) // 如果是静态调用就返回一个拒绝的Promise if(this.status === MyPromise.FULFILLED) return // Promise 的状态一旦确定就不能修改 this.status = MyPromise.REJECT this.result = err @@ -50,3 +52,31 @@ MyPromise.prototype = { return this } } + +// 编写Promise.all([...Promies])静态方法 + +/** + * @description 接受一个Promise的迭代对象,当全部的Promise兑现时,返回一个由兑现值组成的迭代对象 + * 当为空的迭代对象时也会对象一个空的迭代对象 Promise.all([]).then(res=>{console.log(res)}) res = [] + */ +MyPromise.all = function (ps) { + if(typeof ps[Symbol.iterator] !== 'function') throw new Error("传递一个内容为Promise实例的可迭代对象") + var n = ps.length + var rs = [] + for(var i = 0; i < n; i++) { + (function(i){ + ps[i].then(res=>{ + rs[i] = res + }, err=>{ + // all只要出现拒绝,就立马返回第一个拒绝的内容 + this.status = MyPromise.REJECT; + this.result = err + }) + }).call(this, i) + } + if (this.status === MyPromise.REJECT) return this + + this.status = MyPromise.FULFILLED + this.result = rs + return this +}