DEV Community

Cover image for Multiple fetches + params
Jorge Arraga
Jorge Arraga

Posted on

Multiple fetches + params

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 }
}
Enter fullscreen mode Exit fullscreen mode

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}`))
})
Enter fullscreen mode Exit fullscreen mode

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)
    })
}
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

You can use Promise.allSettled() instead of Promise.all(), the differences is explained by Victor in this post:

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()
Enter fullscreen mode Exit fullscreen mode

👋🏽

Top comments (0)