由于Promise的链式回调实在太难,先尝试 Promise.all 的写法

需求分析

  • 接收一个 Promise 数组作为参数
  • 全部 Promise resolve 则返回 结果数组
  • 任意一个 Promise reject 则:有 catch 捕获,无 catch 直接抛出错误
  • 返回一个 thenable 的Promise
  • 如果传入的参数非 Promise 则直接返回值

image.png

先看下正常的Promise的返回(也作为测试代码)

  1. Promise.all([
  2. new Promise((resolve) => {
  3. resolve(1)
  4. }),
  5. new Promise((resolve) => {
  6. resolve(2)
  7. })
  8. ]).then(res => {
  9. console.log('res', res)
  10. })
  11. Promise.all([
  12. new Promise((resolve, reject) => {
  13. reject(1)
  14. }),
  15. new Promise((resolve) => {
  16. resolve(2)
  17. })
  18. ]).then(res => {
  19. console.log('res', res)
  20. })
  21. Promise.all([
  22. new Promise((resolve, reject) => {
  23. reject(1)
  24. }),
  25. new Promise((resolve) => {
  26. resolve(2)
  27. })
  28. ]).then(res => {
  29. console.log('res', res)
  30. }).catch(error => {
  31. console.log('error')
  32. })

image.png

代码

  1. const promiseAll = (pArr) => {
  2. let count = 0
  3. let res = []
  4. return new Promise((resolve, reject) => {
  5. pArr.forEach((item, index) => {
  6. if (item instanceof Promise) {
  7. item.then(data => {
  8. res[index] = data
  9. ++count
  10. if (count === pArr.length) {
  11. resolve(res)
  12. }
  13. }, reject)
  14. } else {
  15. res[index] = item
  16. ++count
  17. }
  18. })
  19. })
  20. }

测试

  1. promiseAll([
  2. new Promise((resolve) => {
  3. setTimeout(() => {
  4. resolve(1)
  5. }, 3000)
  6. }),
  7. new Promise((resolve) => {
  8. resolve(2)
  9. })
  10. ]).then(res => {
  11. console.log('res', res)
  12. })
  13. promiseAll([
  14. new Promise((resolve, reject) => {
  15. reject(1)
  16. }),
  17. new Promise((resolve) => {
  18. resolve(2)
  19. })
  20. ]).then(res => {
  21. console.log('res', res)
  22. }).catch(e => {
  23. console.log('处理reject', e)
  24. })
  25. promiseAll([
  26. 1,
  27. new Promise((resolve, reject) => {
  28. setTimeout(() => {
  29. reject(1)
  30. }, 3000)
  31. }),
  32. 2,
  33. new Promise((resolve) => {
  34. resolve(2)
  35. }),
  36. 3,
  37. ]).then(res => {
  38. console.log('res', res)
  39. }).catch(error => {
  40. console.log('error')
  41. })