I have 4 links, each of them containing one, distinct JSON object. I want to fetch and then place all of them inside of the empty array. I came up with this(I omited async/await):
let arr = [];
let iter = 0;
const FIXED_QUANTITY = 4;
while(iter < FIXED_QUANTITY) {
const res = axios.get(`/data/${iter}.json`);
arr = [...arr, res.data.body];
iter++;
}
And my question is - is it possible to make this code a bit more elegant, perhaps using higher order functions?
You could try something like this maybe?
const urls = [];
const FIXED_QUANTITY = 4;
const iter = 4;
while (iter < FIXED_QUANTITY) {
urls.push(`/data/${iter}.json`);
}
const arr = await Promise.all([...urls.map(url => axios.get(url))]).map(
res => res.data.body
);
You can use the function Array.from
as follow:
let arr = Array.from({length: FIXED_QUANTITY}, async (_, iter) => (await axios.get(`/data/${iter}.json`)).data.body);
This approach generates an array with the following structure:
[{}, {}, ..., {}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.