skip to Main Content

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


  1. Chosen as BEST ANSWER

    The body of an async function can be thought of as being split by zero or more await expressions. Top-level code, up to and including the first await expression (if there is one), is run synchronously. In this way, an async function without an await expression will run synchronously. If there is an await expression inside the function body, however, the async function will always complete asynchronously.

    MDN


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

    export async function getPostData(id) {
        const fullPath = path.join(postsDirectory, `${id}.md`);
        const fileContents = await fs.readFile(fullPath, 'utf8');
        const matterResult = matter(fileContents);
        return {
            id,
            ...matterResult.data,
        };
    }
    

    This function would be rewritten in JS using Promise – ((very very simplified rewrite, not actual one))

    export function getPostData(id) {
      return new Promise(async(resolve, reject) => { // async here, is just for showing how this is treated. Actual rewrite uses generators and state machine. This is only for simplification of example.
        try {  
           const fullPath = path.join(postsDirectory, `${id}.md`);
           const fileContents = await fs.readFile(fullPath, 'utf8');
           const matterResult = matter(fileContents);
           return resolve({
               id,
               ...matterResult.data,
           });
        } catch (err) { return reject(err); }
      });
    }
    

    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 returns Promise (or PromiseLike) object, normal functions not always. Also in async functions you can use await.

    async and await together make asynchronous code execution written in a manner reassembling linear written code.

    function async name() {
      await command1();
      await command2();
    }
    

    Normally would be written (using promises)

    function name() {
      command1().then(() => {
        command2().then(() => {});
      });
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search