自学内容网 自学内容网

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

            }

          }

        );

      });

    });

  }

原文地址:https://blog.csdn.net/qq_73270720/article/details/145291567

免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!