Suppose we need get data from multiple endpoints and proccess all toghether when all requests are finished.
Together with the request we need to pass other parameters to identify them or do something else.
In order to make a requests adding parameters, we'll create our own function that will contain the fetch.
const ownFetch = async (url, params) => {
const res = await fetch(url)
const data = await res.json()
return { data, params }
}
Now we can create an empty array of requests (promises), I'll use jsonplaceholder to get fake info and test code.
Suppose we want to take somethings todos, and each todo has its respective id and thus its own endpoint.
let requests = []
let todos = [1, 3, 5, 10]
todos.forEach((id, i) => {
requests.push(ownFetch(`https://jsonplaceholder.typicode.com/todos/${id}`, `Request #${i+1}`))
})
The final step is to run all the requests through the Promise.all() function and get results:
const run = async () => {
const results = await Promise.all(requests)
results.forEach(result => {
console.log(result)
})
}
The result:
{
data: {
userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false
},
params: 'Request #0'
}
{
data: {
userId: 1,
id: 3,
title: 'fugiat veniam minus',
completed: false
},
params: 'Request #1'
}
{
data: {
userId: 1,
id: 5,
title: 'laboriosam mollitia...',
completed: false
},
params: 'Request #2'
}
{
data: {
userId: 1,
id: 10,
title: 'illo est ratione...',
completed: true
},
params: 'Request #3'
}
You can use Promise.allSettled() instead of Promise.all(), the differences is explained by Victor in this post:
🤝 Promise.allSettled() VS Promise.all() in JavaScript 🍭
Victor de la Fouchardière ・ Aug 16 '20
I leave you the complete code:
const ownFetch = async (url, params) => {
const res = await fetch(url)
const data = await res.json()
return { data, params }
}
let requests = []
let todos = [1, 3, 5, 10]
todos.forEach((id, i) => {
requests.push(ownFetch(`https://jsonplaceholder.typicode.com/todos/${id}`, `Request #${i}`))
})
const run = async () => {
const results = await Promise.all(requests)
results.forEach(result => {
console.log(result)
})
}
run()
👋🏽
Top comments (0)