promise all

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>promise.all</title>
  </head>
  <body>
    <script>
      let link = `https://github.com/shfshanyue/Daily-Question/issues/500`;
      function pAll(_promises) {
        return new Promise((resolve, reject) => {
          // Iterable => Array
          const promises = Array.from(_promises);
          // 结果用一个数组维护
          const r = [];
          const len = promises.length;
          let count = 0;
          for (let i = 0; i < len; i++) {
            // Promise.resolve 确保把所有数据都转化为 Promise
            Promise.resolve(promises[i])
              .then(o => {
                // 因为 promise 是异步的,保持数组一一对应
                r[i] = o;

                // 如果数组中所有 promise 都完成,则返回结果数组
                if (++count === len) {
                  resolve(r);
                }
                // 当发生异常时,直接 reject
              })
              .catch(e => reject(e));
          }
        });
      }
    </script>
    <script>
      const sleep = seconds => new Promise(resolve => setTimeout(() => resolve(seconds), seconds));
    </script>
    <script>
      function promiseAll(_promises) {
        return new Promise((resolve, reject) => {
          const promises = [..._promises];
          const arr = [];
          let count = 1;
          for (let i = 0; i < promises.length; i++) {
            Promise.resolve(promises[i]).then(
              data => {
                arr[i] = data;
                if (++count === promises.length) {
                  resolve(arr);
                }
              },
              err => {
                reject(err);
              }
            );
          }
        });
      }
    </script>
    <script>
      function makeIterator(array) {
        let nextIndex = 0;
        return {
          next: function () {
            return nextIndex < array.length
              ? {
                  value: array[nextIndex++],
                  done: false
                }
              : {
                  done: true
                };
          }
        };
      }

      let it = makeIterator(['', '']);

      console.log(it.next().value); // '哟'
      console.log(it.next().value); // '呀'
      console.log(it.next().done); // true
    </script>
  </body>
</html>

 

posted @ 2022-05-04 14:24  苹果π  阅读(81)  评论(0编辑  收藏  举报