Next.js Discord

Discord Forum

How to fetch multiple requests in parallel in RSC?

Answered
Australian Freshwater Crocodile posted this in #help-forum
Open in Discord
Avatar
Australian Freshwater CrocodileOP
Hey guys, is there a built-in way to fetch multiple requests in parallel in RSC?

Example:
export async function Example() {
  const someStuff = await getSomeStuff();
  const otherStuff = await getOtherStuff();

  return (

  )
}

These requests are being executed after each other upon completion

But this could be optimized if requests would not be executed in parallel and we can do it like this:
export async function Example() {
  const [someStuff, otherStuff] = await Promise.all([
    getSomeStuff(),
    getOtherStuff(),
  ]);

  return (

  )
}


I was wondering, maybe there is a better way of doing that? And is it even worth doing?

4 Replies

Avatar
Holland Lop
using Promise.all() make the requests parallel, but for genrating the overall response, you should wait for both responses to be resolved, but if the data is from seperate parts of app, you can use parallel routes to stream each response when it's ready seperately
Answer
Avatar
Tonkinese
Create one function that takes in multiple async functions, pass them in without the 'await', but apply the 'await' to the function you're passing them into, and inside of that function use the Promise.all() like alighafoorzade said.
Avatar
Australian Freshwater CrocodileOP
Thanks guys!