Next.js Discord

Discord Forum

How to build a route handler that uses Promise.all?

Unanswered
Blanc de Hotot posted this in #help-forum
Open in Discord
Blanc de HototOP
Next13+ question!
Hi folks! I have an issue where my route handler doesn't seem to be fetching my requests. (I get exited to the catch statement if I wrap it in a try/catch. Is there a bug in my code I'm not understanding here?

export async function GET(
  request: Request,
  { params }: { params: { itemId: string } }
) {
  const itemId = Number(params.itemId);

  if (Number.isNaN(itemId)) {
    return NextResponse.json(
      { 
        error: 'Invalid ID.'
      },
      {
        status: 500,
      }
    );
  }

  const [a, b, c, d] =
    await Promise.all([
      promiseA, promiseB, promiseC, promiseD
    ]);

  const reducedItems = b.results.reduce(
    (acc, item) => ({
      ...acc,
      [item.condition]: [...(acc[item.condition] || []), item],
    }),
    {} as Record<string, ItemC[]>,
  );

  const allItems = [a,b,c,d];

  return NextResponse.json(
    {
      items: allItems,
      reducedItems: reducedItems,
    },
    {
      status: 200,
      headers: {
        'Content-Type': 'application/json',
      },
    }
  );
}

9 Replies

Are one of your promises getting rejected?
With what your describing it indicates one of your promises are getting rejected. I cant see what your promises are doing so I cant comment on that.
Cimarrón Uruguayo
try awaiting each promise individually to see which one is being rejected
Blanc de HototOP
when i convert it to a manual API route by restructuring the above file to be hosted like:
|-app
|---(my entire nextjs app)
|-pages
|---api
|-----[itemId].ts

and rename the GET function to something else it works fine :')
it doesn't like this structure however:
|-app
|---api
|-----route.ts
:pepe_sad:
I mean pages router is not app router. Im confused what you mean.
Its rather bad pratice to have an api route at 'api' lol
/api/something. /api shouldnt really be an endpoint