一、promise

二、promise.all

  1. // 输入不仅仅只有Array
  2. function promiseAll (args) {
  3. return new Promise((resolve, reject) => {
  4. const promiseResults = [];
  5. let iteratorIndex = 0;
  6. // 已完成的数量,用于最终的返回,不能直接用完成数量作为iteratorIndex
  7. // 输出顺序和完成顺序是两码事
  8. let fullCount = 0;
  9. // 用于迭代iterator数据
  10. for (const item of args) {
  11. // for of 遍历顺序,用于返回正确顺序的结果
  12. // 因iterator用forEach遍历后的key和value一样,所以必须存一份for of的 iteratorIndex
  13. let resultIndex = iteratorIndex;
  14. iteratorIndex += 1;
  15. // 包一层,以兼容非promise的情况
  16. Promise.resolve(item).then(res => {
  17. promiseResults[resultIndex] = res;
  18. fullCount += 1;
  19. // Iterator 接口的数据无法单纯的用length和size判断长度,不能局限于Array和 Map类型中
  20. if (fullCount === iteratorIndex) {
  21. resolve(promiseResults)
  22. }
  23. }).catch(err => {
  24. reject(err)
  25. })
  26. }
  27. // 处理空 iterator 的情况
  28. if(iteratorIndex===0){
  29. resolve(promiseResults)
  30. }
  31. }
  32. )
  33. }
  34. if (!Promise.all) Promise.all = promiseAll;


三、promise.allSettled

  1. export function allSettled (promises) {
  2. return new Promise(function(resolve, reject) {
  3. if (!Array.isArray(promises)) {
  4. return reject(
  5. new TypeError("arguments must be an array")
  6. );
  7. }
  8. var resolvedCounter = 0;
  9. var promiseNum = promises.length;
  10. var resolvedValues = new Array(promiseNum);
  11. for (var i = 0; i < promiseNum; i++) {
  12. (function(i) {
  13. Promise.resolve(promises[i]).then(
  14. function(value) {
  15. resolvedCounter++;
  16. resolvedValues[i] = value;
  17. if (resolvedCounter == promiseNum) {
  18. return resolve(resolvedValues);
  19. }
  20. },
  21. function(reason) {
  22. resolvedCounter++;
  23. resolvedValues[i] = reason;
  24. if (resolvedCounter == promiseNum) {
  25. return reject(reason);
  26. }
  27. }
  28. );
  29. })(i);
  30. }
  31. });
  32. };