高级前端
js
【Q241】如何使用 async/await 实现 Promise.all 的效果

如何使用 async/await 实现 Promise.all 的效果

更多描述 如获取三个用户的信息,使用 Promise.all 的写法

const users = await Promise.all(getUser(1), getUser(2), getUser(3));

那如何不使用 Promise.all 实现以上效果

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 242 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

使用 async/await 实现

const user1 = getUser(1);
const user2 = getUser(2);
const user3 = getUser(3);
 
const u1 = await user1;
const u2 = await user2;
const u3 = await user3;

Author 回答者: Misxiao (opens in a new tab)

const all = (list) => {
    const res = new Promise((resolve, reject) => {
        let length = list && list.length
        let count = 0
        let result = []
        if(!list || list.length === 0) {
            resolve(result)
        }
        list.forEach(async (item, index) => {
            try {
                const res = await item
                result[index] = res
                count ++
                if(count === length) {
                    resolve(result)
                }
            } catch(err) {
                reject(err)
            }
        });
    })
    return res
}

使用 async/await 实现

const user1 = getUser(1);
const user2 = getUser(2);
const user3 = getUser(3);
 
const u1 = await user1;
const u2 = await user2;
const u3 = await user3;

这个和上面的 Promise.all 并不一样吧。Promise.all 是并行操作,await 这个是串行操作

如获取三个用户的信息,使用 Promise.all 的写法

const users = await Promise.all(getUser(1), getUser(2), getUser(3));

那如何不使用 Promise.all 实现以上效果

Promise.all 后面的参数为数组。。。

let req1 = () =>
  fetch(
    `https://github.com/shfshanyue/Daily-Question/issues?page=1&q=is%3Aissue+is%3Aopen`,
  );
 
let req2 = () =>
  fetch(
    `https://github.com/shfshanyue/Daily-Question/issues?page=2&q=is%3Aissue+is%3Aopen`,
  );
 
let req3 = () =>
  fetch(
    `https://github.com/shfshanyue/Daily-Question/issues?page=3&q=is%3Aissue+is%3Aopen`,
  );
 
// promise.all
const res = await Promise.all([req1(), req2(), req3()]);
 
const res1 = req1();
const res2 = req2();
const res3 = req3();
 
// await
const u1 = await res1;
const u2 = await res2;
const u3 = await res3;

image

所以这个题的答案是

tan90° 不存在

Author 回答者: jeff-wangzhen (opens in a new tab)

看了一篇这个,好像可以 https://blog.csdn.net/github_38589282/article/details/79268484 (opens in a new tab)

Author 回答者: iamphc (opens in a new tab)

如有错误,欢迎指正

async function foo(promise) {
  const t = [];
  for (let p of promise) {
    // 检查传参
    if (p instanceof Promise === false) {
      throw new Error("传参错误");
    }
    // 并行触发
    (async () => {
      try {
        const r = await p;
        t.push(r);
      } catch (err) {
        // 捕获异常
        return err;
      }
    })();
  }
  // 轮询
  const res = await new Promise((resolve) => {
    const timer = setInterval(() => {
      if (t.length === promise.length) {
        clearInterval(timer);
        resolve(t);
      }
    }, 1000);
  });
  return res;
}

Author 回答者: justorez (opens in a new tab)

所以这个题的答案是

tan90° 不存在

@ghost

image

<script>
  async function fn() {
    const req = (i) =>
      fetch(
        `https://github.com/shfshanyue/Daily-Question/issues?page=${i}&q=is%3Aissue+is%3Aopen`,
        {
          mode: "no-cors",
        },
      );
 
    // promise.all
    const res = await Promise.all([req(1), req(2), req(3)]);
 
    // await
    const res1 = req(4);
    const res2 = req(5);
    const res3 = req(6);
    const u1 = await res1;
    const u2 = await res2;
    const u3 = await res3;
  }
  fn();
</script>