使用 Promise.all 同时发起多个请求

博客园 @四季留歌。 前置技术条件:es6 Promisees7 async、await


有时候不想在 async 函数中写太多 await 语句,例如:

const doSth = async () => {
  const response1 = await fetch('/api1')
  const json1 = await response1.json()
  const response2 = await fetch('/api2')
  const buffer = await response2.arrayBuffer()
  // ...
}

可以使用 Promise.all 来实现同时请求:

// 如果都是要转成 json
const urls = ['/api1', '/api2']
const doSth = async () => {
  const results = await Promise.all(urls.map(
    url => fetch(url).then(response => response.json()) // 注意这个箭头函数,是 map 所执行的
  ))
  console.log(results) // 俩 json
}

如果每个接口请求返回的数据格式要求不太一样的话,那就要稍微麻烦一点

const requests = [
  { url: '/api1', format: 'json' },
  { url: '/api2', format: 'arrayBuffer' }
]
const doSth = async () => {
  const results = await Promise.all(requests.map(
    request => {
      const { url, format } = request
      return fetch(url).then(response => response[format]()) // 注意此处使用计算属性来获取转换函数
    }
  ))
  console.log(results) // 一个 json,一个 arrayBuffer
}
posted @ 2021-08-23 16:42  岭南灯火  阅读(3116)  评论(0编辑  收藏  举报