学习链接

40+ 大厂常考 JS 手写题系列【摸鱼必备】

死磕 36 个 JS 手写题(搞懂后,提升真的大)

网道教程:Promise.all()

Promise.all

Promise.all - 图1

补充:

  1. // Little known fact: Array.prototype itself is an array:
  2. Array.isArray(Array.prototype); // true
  1. Promise.myAll = promiseArr => {
  2. return new Promise((resolve, reject) => {
  3. if (!promiseArr[Symbol.iterator]) {
  4. throw new TypeError(`${promiseArr} is not iterable`) // 需要iterator接口
  5. }
  6. if (!Array.isArray(promiseArr)) {
  7. promiseArr = Array.from(promiseArr); // 根据 iterator 接口转为数组
  8. }
  9. let result = [], count = 0; // count 记录fulfilled数量
  10. promiseArr.forEach((p, i) => {
  11. Promise.resolve(p).then(res => { // 转为 Promise 对象
  12. count++; // 进入then的回调, fulfilled的实例数加一
  13. result[i] = res;
  14. if (count === promiseArr.length) {
  15. resolve(result);
  16. }
  17. }, err => {
  18. reject(err);
  19. })
  20. })
  21. })
  22. }

测试

  1. const promise1 = Promise.resolve(3);
  2. const promise2 = 42;
  3. const promise3 = new Promise((resolve, reject) => {
  4. setTimeout(resolve, 1000, 'foo');
  5. });
  6. Promise.myAll([promise1, promise2, promise3]).then(val => console.log(val));
  7. // [3, 42, 'foo']
  8. Promise.all([promise1, promise2, promise3]).then(val => console.log(val));
  1. const p1 = new Promise((resolve, reject) => {
  2. resolve('hello');
  3. })
  4. .then(result => result)
  5. .catch(e => e);
  6. const p2 = new Promise((resolve, reject) => {
  7. throw new Error('报错了');
  8. })
  9. .then(result => result)
  10. .catch(e => e);
  11. Promise.myAll([p1, p2])
  12. .then(result => console.log(result))
  13. .catch(e => console.log(e));
  14. // ["hello", Error: 报错了]
  15. Promise.all([p1, p2])
  16. .then(result => console.log(result))
  17. .catch(e => console.log(e));
  1. // 验证 iterator 接口
  2. const p1 = Promise.resolve(3);
  3. const p2 = 42;
  4. const p3 = new Promise((resolve, reject) => {
  5. setTimeout(resolve, 1000, 'foo');
  6. });
  7. const promiseArr = [p1, p2, p3];
  8. let num = 0;
  9. const promiseIterator = {
  10. [Symbol.iterator]() {
  11. return {
  12. next() {
  13. if (num < promiseArr.length) {
  14. return { done: false, value: promiseArr[num++] }
  15. }
  16. return { done: true, value: undefined }
  17. }
  18. }
  19. }
  20. };
  21. // Promise.All(promiseIterator)
  22. // .then(result => console.log(result))
  23. // .catch(e => console.log(e));
  24. // [3, 42, 'foo']
  25. Promise.myAll(promiseIterator)
  26. .then(result => console.log(result))
  27. .catch(e => console.log(e));