Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现Promise.all()、race()、any() #40

Open
mtonhuang opened this issue Jan 11, 2023 · 0 comments
Open

实现Promise.all()、race()、any() #40

mtonhuang opened this issue Jan 11, 2023 · 0 comments
Assignees

Comments

@mtonhuang
Copy link
Owner

mtonhuang commented Jan 11, 2023

实现Promise.all()

1、Promise.all​​​ 接受一个数组,返回值是一个新的 ​​Promise​​ 实例

Promise.MyAll = function (promises) {
  return new Promise((resolve, reject) => {

  })
}

2、需要一个数组来收集参数数组中所有 ​​Promise​​​ 实例,即实例都成功,​​Promise.all​​ 才成功

Promise.MyAll = function (promises) {
  let arr = []
  return new Promise((resolve, reject) => {
    promises.forEach((item, i) => {
      Promise.resolve(item).then(res => {
        arr[i] = res
      })
    }) 
  })
}

3、兼容处理失败的情况

Promise.MyAll = function (promises) {
  let arr = [],
    count = 0
  return new Promise((resolve, reject) => {
    promises.forEach((item, i) => {
      Promise.resolve(item).then(res => {
        arr[i] = res
        count += 1
        if (count === promises.length) resolve(arr)
      }).catch(reject)
    })
  })
}
// 或者这样捕获错误
Promise.MyAll = function (promises) {
  let arr = [],
    count = 0
  return new Promise((resolve, reject) => {
    promises.forEach((item, i) => {
      Promise.resolve(item).then(res => {
        arr[i] = res
        count += 1
        if (count === promises.length) resolve(arr)
      }, reject)
    })
  })
}

实现Promise.race()

// 实现Promise.race 输出最快promise
Promise.testRace = function (promiseArr) {
  return new promise((resolve, reject) => {
    promiseArr.forEach((item) => {
      Promise.resolve(item)
        .then((res) => {
          resolve(res);
        })
        .catch(() => {
          reject();
        });
    });
  });
};

实现Promise.any()

// 实现Promise.any 全部失败输出,否则任意一个
Promise.testAny = function (promiseArr) {
  return new promise((resolve, reject) => {
    let arr = [],
      num = 0;
    promiseArr.forEach((item, index) => {
      Promise.resolve(item)
        .then()
        .catch((err) => {
          arr[index] = { status: 'reject', val: err };
          num += 1;
          if (num === promiseArr.length) reject(new Error('没有promise成功'));
        });
    });
  });
};```
@mtonhuang mtonhuang self-assigned this Jan 11, 2023
@mtonhuang mtonhuang changed the title 实现Promise.all()、Promise.race()、Promise.any() 实现Promise.all()、race()、any() Jan 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant