I use nextjs
in conjunction with next-redux-wrapper
and for seo pages I dispatch actions as described in the documentation for asynchronous actions:
export const getServerSideProps = wrapper.getServerSideProps(
(store) =>
async ({ locale, query }) => {
await store.dispatch(getInfo())
await store.dispatch(getCategories())
await store.dispatch(getTutorialLink())
await store.dispatch(getCatalog({ category_id: query.category_id ?? null }))
return {
props: {
...(await serverSideTranslations(locale)),
},
}
}
)
All actions usually use an API, and it appears on the server that I pull the data in blocking mode, waiting for one request to be executed, and then another, so I was wondering if this code would increase the download speed:
export const getServerSideProps = wrapper.getServerSideProps(
(store) =>
async ({ locale, query }) => {
await Promise.all([
store.dispatch(getInfo()),
store.dispatch(getCategories()),
store.dispatch(getTutorialLink()),
store.dispatch(getCatalog({ category_id: query.category_id ?? null }))
])
return {
props: {
...(await serverSideTranslations(locale, ['draw'])),
},
}
}
)
In my opinion, this should run all exins asynchronously without blocking each other. How normal is the story?
Yes, it is absolutely a good idea to use Promise.all
, as long as all those actions are independent from each other.
The reason you sometimes need to use successive await
s like in your first example is if one of them depends on the value returned by the previous one. In such cases you cannot run them in parallel so you need to use successive await
s.