欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > js手写-promise的静态方法

js手写-promise的静态方法

2025/1/22 11:52:32 来源:https://blog.csdn.net/qq_73270720/article/details/145291567  浏览:    关键词:js手写-promise的静态方法

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));}});});});}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com