resolve/reject
在之前实现的mypromise基础上
static resolve(value){return new MyPromise((resolve)=>resolve(value))}static reject(reason){return new MyPromise((resolve,reject)=>reject(reason))}}MyPromise.resolve("成功").then((res) => {console.log(res);})MyPromise.reject("失败").catch((err) => {console.log(err);})
all/allSettled
static all(promises){return new MyPromise((resolve,reject)=>{//存储遍历的结果let values = []promises.forEach((promise)=>{promise.then(res=>{//收集所有成功的结果values.push(res)//如果全都成功if(values.length == promises.length){resolve(values)}},(err)=>{//一旦有一个失败就是失败的reject(err)})})})}static allSettled(promises) {return new MyPromise((resolve, reject) => {//存储遍历的结果let values = [];promises.forEach((promise) => {promise.then((res) => {//收集所有成功的结果values.push({status: "fulfilled",value: res,});if (values.length == promises.length) resolve(values);},(err) => {values.push({status: "rejected",value: err,});if (values.length == promises.length) resolve(values);});});});}
race/any
static race(promises) {return new MyPromise((resolve, reject) => {promises.forEach((promise) => {promise.then((res) => {resolve(res);},(err) => {reject(err);});});});}static any(promises) {return new MyPromise((resolve, reject) => {const reasons = [];promises.forEach((promise) => {promise.then((val) => {resolve(val);},(err) => {reasons.push(err);if (reasons.length == promises.length) {reject(new AggregateError(reasons));}});});});}