shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 510 forks source link

【Q241】如何使用 async/await 实现 Promise.all 的效果 #242

Open shfshanyue opened 4 years ago

shfshanyue commented 4 years ago

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

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

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

shfshanyue commented 4 years ago

使用 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
Misxiao commented 4 years ago
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
}
ghost commented 4 years ago

使用 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 这个是串行操作

ghost commented 4 years ago

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

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

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

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

ghost commented 4 years ago
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

ghost commented 4 years ago

所以这个题的答案是

tan90° 不存在

jeff-wangzhen commented 2 years ago

看了一篇这个,好像可以 https://blog.csdn.net/github_38589282/article/details/79268484

iamphc commented 1 year ago

如有错误,欢迎指正

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
}
justorez commented 1 year ago

所以这个题的答案是

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>