Certainly! If the third query returns an object instead of a singular value, we can still use Promise.all to parallelize our queries. We just need to adjust how we destructure the results. Here's how we can refactor the code example:
const [resultOne, resultTwo, { propertyA, propertyB }] = await Promise.all([
queryOne(tx, paramOne),
queryTwo(tx, paramTwo),
queryThree(tx, paramThree)
]);
In this refactored version:
resultOne and resultTwo remain as they were, assuming they return singular values.
- For the third query result, we're using object destructuring to extract specific properties (
propertyA and propertyB) from the returned object.
If you want to keep the entire object returned by the third query, you can do this instead:
const [resultOne, resultTwo, resultThree] = await Promise.all([
queryOne(tx, paramOne),
queryTwo(tx, paramTwo),
queryThree(tx, paramThree)
]);
const { propertyA, propertyB } = resultThree;
This approach aligns with the Next.js best practices for parallel data fetching, as mentioned in the Next.js documentation. It allows you to initiate all queries simultaneously, potentially improving performance by reducing the overall execution time.
Remember, the order of the results in the array returned by Promise.all corresponds to the order of the promises in the input array, regardless of which promise resolves first. This ensures that each result is correctly assigned to its corresponding variable.