Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Would it be more productive to use await Promis.all() instead of await somePromis?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 awaits 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 awaits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading