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 使用、原理实现及错误处理 #35

Open
hanyueqiang opened this issue Dec 21, 2020 · 0 comments
Open

介绍下 Promise.all 使用、原理实现及错误处理 #35

hanyueqiang opened this issue Dec 21, 2020 · 0 comments

Comments

@hanyueqiang
Copy link
Owner

Promise.all()的参数是传入一个数组,数组的值是Promise对象,如果不是,就会先调用Promise.resolve方法,将参数转为 Promise 实例,这个函数返回一个Promise对象
这个函数顾名思义就是检查传入的所有数组是否都执行成功,如果都成功那么这个函数返回的Promise对象进入resolve状态并将所有promise成功的参数组成一个数组传给resolve函数,如果其中任何一个失败,那么就进入reject状态,并将第一个reject的promise的参数传给Promise.all返回的promise对象的reject函数

function promiseAll(arr = []) {
  return new Promise((resolve, reject) => {
    const result = [],
      len = arr.length;
    arr.forEach(item => {
      Promise.resolve(item).then(
        res => {
          result.push(res);
          if (result.length === len) {
            resolve(result);
          }
        },
        err => {
          reject(err);
        }
      );
    });
  });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant