0

I have a list of IDs i.e: [3,6,7] I want to fetch all objects from api which have 3,6 and 7 as id. I can fetch it with only one ID. like this:

 const response = await fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id: 7,
    }),
  });

How can I fetch with different ids? thanks in advance.

1
  • 1
    use response = await Promise.all([fetch(...id1), fetch(...id2), fetch(...id3)]) Commented Oct 29, 2019 at 9:54

3 Answers 3

1

You can use Promise.all https://developer.mozilla.org/vi/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

const promises = [3,6,7].map(id => {
  return fetch(`http://localhost:3000/api`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify({
      id,
    }),
  })
})

const response = await Promise.all(promies)
console.log(responese)
Sign up to request clarification or add additional context in comments.

Comments

0

fetch(...) returns a promise.

await fetch(...) Gets the result of that returned promise.

So to do more than one call at once you need to handle multiple promises.

const p1 = fetch(...)
const p2 = fetch(...)
const p3 = fetch(...)

const [p1Result, p2Result, p3Result] = await Promise.all(p1, p2, p3);

Will put the results of those fetchers in the Result consts.

Comments

0

It is best to put you're requests in an Array and wait for them to finish.

const myLogic = () => {
    //Put ids in function and get responses
    getByIds([3,6,7]).then(responses => {
        console.log(responses);        
    });
}

const getByIds = async (ids) => {
    //put all promises in an Array so we can let them run and be awaited
    //await is bad practise in loops and usually does not work
    let requests = [];
    let responses = [];

    for (let id in ids)
        requests.push(fetch(`http://localhost:3000/api`, {
            method: 'POST',
            body: JSON.stringify({ id }),
            headers: { 'Content-Type': 'application/json; charset=utf-8' },
        })
            //Add response to array
            .then(response => responses.push(response))
            .catch(err => console.log(err)));

    //Await all requests
    await Promise.all(requests);

    //return all responses
    return responses;
}

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.