0

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?

2 Answers 2

1

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
);
Sign up to request clarification or add additional context in comments.

Comments

0

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:

[{}, {}, ..., {}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.