Promise

1、Promise.allSettled

  1. Promise.allSettled = Promise.allSettled || function (arr) {
  2. let P = this;
  3. return new P(function (resolve, reject) {
  4. if (Object.prototype.toString.call(arr) !== '[object Array]') {
  5. return reject(
  6. new TypeError(
  7. typeof arr +
  8. ' ' +
  9. arr +
  10. ' ' +
  11. ' is not iterable(cannot read property Symbol(Symbol.iterator))'
  12. )
  13. );
  14. }
  15. let args = Array.prototype.slice.call(arr);
  16. if (args.length === 0) return resolve([]);
  17. let arrCount = args.length;
  18. function resolvePromise(index, value) {
  19. if (typeof value === 'object') {
  20. let then = value.then;
  21. if (typeof then === 'function') {
  22. then.call(
  23. value,
  24. function (val) {
  25. args[index] = { status: 'fulfilled', value: val };
  26. if (--arrCount === 0) {
  27. resolve(args);
  28. }
  29. },
  30. function (e) {
  31. args[index] = { status: 'rejected', reason: e };
  32. if (--arrCount === 0) {
  33. resolve(args);
  34. }
  35. }
  36. );
  37. }
  38. }
  39. }
  40. for (let i = 0; i < args.length; i++) {
  41. resolvePromise(i, args[i]);
  42. }
  43. });
  44. };