如何在javascript中发起多个请求
Yakim Zhang

在 Javascript 中发出 HTTP 请求(API 调用)可以通过多种方式完成,例如使用浏览器原生的 fetch 功能、jQuery$.ajax 、axios 等。

还有一些选项是为 Reactreact-query 等不同的后端和前端框架量身定制的。

使用方法都差不多:

  1. 你发出一个请求,返回一个 Promise
  2. 在 Promise 没有结果前不能使用数据

单个 API 的调用

1
2
3
4
5
6
7
8
9
10
async function getData (){

const url = //... api

const response = await fetch(url)

const data = await response.json() object

// 使用data,例如 data.map
}

两个 API 的调用

假设,现在需要拿到 2 个 API 的数据,才能执行接下来的工作。
最粗暴的方法是一个接一个的请求,见下面的代码。

1
2
3
4
5
6
7
8
9
10
11
12
13

async function getData(){
const url1 = //...
const url2 = //...

const response1 = await fetch(url1)
const data1 = await response1.json()

const response2 = await fetch(url2)
const data2 = await response1.json()

}

这种串行方式一个请求返回结果后,才去请求另外一个,很低效。

使用 Promise.all()并行
2 个请求同时发出,当 2 个请求都返回成功结果的时候,才返回 responses。

1
2
3
4
5
6
7
8
9
10
async function getData(){
const url1 = //...
const url2 = //...

const responses = await Promise.all([fetch(url1), fetch(url2)])

const data1 = await responses[0].json()
const data2 = await responses[1].json()
}