promise.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict";
  2. function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  3. var isArray = Array.isArray;
  4. Promise.all = function (arr) {
  5. return new Promise(function (resolve, reject) {
  6. if (!isArray(arr)) {
  7. return reject(new TypeError('Promise.all accepts an array'));
  8. }
  9. var args = Array.prototype.slice.call(arr);
  10. if (args.length === 0) {
  11. return resolve([]);
  12. }
  13. var remaining = args.length;
  14. function res(i, val) {
  15. try {
  16. if (val && (_typeof(val) === 'object' || typeof val === 'function')) {
  17. var then = val.then;
  18. if (typeof then === 'function') {
  19. then.call(val, function (_val) {
  20. res(i, _val);
  21. }, reject);
  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 (var i = 0; i < args.length; i++) {
  34. res(i, args[i]);
  35. }
  36. });
  37. };