zoukankan      html  css  js  c++  java
  • 使用 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
    }
    
  • 相关阅读:
    FastDFS
    MYSQL日常操作
    SVN安装
    mysql主主配置
    MySQL优化
    nginx反向代理tomacat+keepalived实现动静分离、负载均衡、高可用
    nginx故障及处理
    nginx配置检测及安全配置
    nginx基本优化
    大金空调适配器
  • 原文地址:https://www.cnblogs.com/onsummer/p/15176600.html
Copyright © 2011-2022 走看看