从多个 API 端点获取数据
Fetching data from multiple API endpoints
背景资料
我正在做一个项目,我需要从多个 API 端点获取数据,每个端点都有自己的凭据。现在,我正在映射一个包含所有不同凭据的 JSON 数组,并将返回的数据推送到一个空数组,如下所示。
代码
const fetchData = async () => {
dataArray = [];
// Loop through all objects in the array, 'arr' contains all of the different credentials.
arr.map(async (obj) => {
// Defining info to access API.
// Authenticating to API.
// Fetching data from API.
// Returns one array containing one or multiple objects. (data).
/* Pushing first object of the array to dataArray. I would also like to push all objects
if there is more than one! */
dataArray.push(data[0]);
});
// Return array after mapping through arr.
return dataArray;
};
module.exports = { fetchData };
问题
如果我这样做,函数只returns一个空数组。所以它不会等待函数的第一部分(通过 arr 映射)完成。
另一方面,如果我在 fetchData 函数之外的更高级别上声明空数组 (dataArray= [];),它 returns 会获取值。但如果这样做,数组永远不会重置并填满数据。
我该如何解决这个问题?还是有更好的方法来完全做到这一点?
想要的结果
- 函数循环遍历包含凭据的 JSON 数组 ('arr'),并在其中设置每个对象/凭据,登录到 API 和 returns 值。
- 应将这些值收集到一个数组中,该数组将包含所有返回的对象。
- 函数returns这个数组完成后。
在 fetchData 函数中使用 Promise.all
let arr=["credential 1","credential 2","credential 3"]
let requestArr = []
for (var i = arr.length - 1; i >= 0; i--) {
//for example we use axios to send request
requestArr.push(axios(`request with releted credential`))
}
//here we got all the promised request array
let responseArr = await Promise.allSettled(requestArr)
responseArr.then(res => {
// res is a arr of all individual request
[res1, res2]
})
背景资料
我正在做一个项目,我需要从多个 API 端点获取数据,每个端点都有自己的凭据。现在,我正在映射一个包含所有不同凭据的 JSON 数组,并将返回的数据推送到一个空数组,如下所示。
代码
const fetchData = async () => {
dataArray = [];
// Loop through all objects in the array, 'arr' contains all of the different credentials.
arr.map(async (obj) => {
// Defining info to access API.
// Authenticating to API.
// Fetching data from API.
// Returns one array containing one or multiple objects. (data).
/* Pushing first object of the array to dataArray. I would also like to push all objects
if there is more than one! */
dataArray.push(data[0]);
});
// Return array after mapping through arr.
return dataArray;
};
module.exports = { fetchData };
问题
如果我这样做,函数只returns一个空数组。所以它不会等待函数的第一部分(通过 arr 映射)完成。
另一方面,如果我在 fetchData 函数之外的更高级别上声明空数组 (dataArray= [];),它 returns 会获取值。但如果这样做,数组永远不会重置并填满数据。
我该如何解决这个问题?还是有更好的方法来完全做到这一点?
想要的结果
- 函数循环遍历包含凭据的 JSON 数组 ('arr'),并在其中设置每个对象/凭据,登录到 API 和 returns 值。
- 应将这些值收集到一个数组中,该数组将包含所有返回的对象。
- 函数returns这个数组完成后。
在 fetchData 函数中使用 Promise.all
let arr=["credential 1","credential 2","credential 3"]
let requestArr = []
for (var i = arr.length - 1; i >= 0; i--) {
//for example we use axios to send request
requestArr.push(axios(`request with releted credential`))
}
//here we got all the promised request array
let responseArr = await Promise.allSettled(requestArr)
responseArr.then(res => {
// res is a arr of all individual request
[res1, res2]
})