DEV Community

Cover image for Multiple fetches + params
Jorge Arraga
Jorge Arraga

Posted on

2 2

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

👋🏽

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay