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
    }
    
  • 相关阅读:
    迭代器
    LinkedList存储一副扑克牌,实现洗牌功能。
    线程
    堆栈、队列
    路由-第7集
    javascript中split字符串分割函数
    this的用法
    什么是AOP面向切面编程
    Servlet与JSP的区别
    堆(heap)、栈(stack)、方法区(method)
  • 原文地址:https://www.cnblogs.com/onsummer/p/15176600.html
Copyright © 2011-2022 走看看