promise.js 943 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const isArray = Array.isArray
  2. Promise.all = function(arr) {
  3. return new Promise(((resolve, reject) => {
  4. if (!isArray(arr)) {
  5. return reject(new TypeError('Promise.all accepts an array'))
  6. }
  7. const args = Array.prototype.slice.call(arr)
  8. if (args.length === 0) { return resolve([]) }
  9. let remaining = args.length
  10. function res(i, val) {
  11. try {
  12. if (val && (typeof val === 'object' || typeof val === 'function')) {
  13. const then = val.then
  14. if (typeof then === 'function') {
  15. then.call(
  16. val,
  17. (_val) => {
  18. res(i, _val)
  19. },
  20. reject,
  21. )
  22. return
  23. }
  24. }
  25. args[i] = val
  26. if (--remaining === 0) {
  27. resolve(args)
  28. }
  29. } catch (ex) {
  30. reject(ex)
  31. }
  32. }
  33. for (let i = 0; i < args.length; i++) {
  34. res(i, args[i])
  35. }
  36. }))
  37. }