John Jacob
John Jacob

Reputation: 107

Why is getStaticProps() an asynchronous function in Next.js?

Why is getStaticProps() an asynchronous function in Next.js? As I understand it, an async function is one offloaded from the main thread while it executes. This stops the main thread from being unnecessarily held up by functions that can take a while (ex. fetching from a database).

getStaticProps() is executed at build time and therefore doesn't impact the main thread rendering the page in Next.js. I was therefore wondering why it's an asynchronous function. Is this so it doesn't block execution while the application is being built? Thanks.

Upvotes: 0

Views: 861

Answers (1)

AKX
AKX

Reputation: 168986

As I understand it, an async function is one offloaded from the main thread while it executes.

You misunderstand. async is syntactical sugar for a function that returns a Promise. It's not run on a separate thread, and indeed, if you have a very long synchronous function, async functions won't get run.

I was therefore wondering why it's an asynchronous function.

Because it may well need to do asynchronous calls such as getting data from an external source, as e.g. this official example shows.

If it wasn't an async function, it would need to asynchronicity via a callback (which is quite outmoded) to be able to return data after an asynchronous call.

Does it execute in a separate thread on the server while the application is being built?

Likely not (considering Node.js is single-threaded).

Upvotes: 1

Related Questions