Function with async
:
export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const matterResult = matter(fileContents);
return {
id,
...matterResult.data,
};
}
Function without async
:
export function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const matterResult = matter(fileContents);
return {
id,
...matterResult.data,
};
}
I recently got back into NextJS and have forgotten how do these 2 functions would operate with and without async. I will try my best to explain them to see if I am correct:
The function without async will behave synchronously meaning that the constant "fullPath" will execute its function and will not continue to the next variable until it has finished.
The same for the rest of the variables.
The function with async (or asynchronous) will execute the function’s variables at the same time.
However, in this situation, the variable "matterResult" depends on the variable "fileContents" to finish as this one is waiting on the variable "fullPath" to finish executing.
Can I execute this async function without "await" on the variables? What difference will it make? Do these behave in a synchronous way despite these variables being inside an async function?
2
Answers
MDN
NextJS
It executes both functions the same. It checks if the function returned
Promise
or not – it did – it will wait for its execution and use the fulfilled value as return value of the function (or pass the promise further if what it was doing was also asynchronous).Async simplified?
First correct async function would be like that
This function would be rewritten in JS using
Promise
– ((very very simplified rewrite, not actual one))As people in comments already told you, this functions are not really so different, and variables in them are behaving with theirs scopes. What is different is what is returned.
async
functions always returnsPromise
(orPromiseLike
) object, normal functions not always. Also inasync
functions you can useawait
.async
andawait
together make asynchronous code execution written in a manner reassembling linear written code.Normally would be written (using promises)
Which, when you want to return some values, or pass them, or handle errors – can become very complicated code, but using
async&await
it becomes quite clear/clean.