Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding async/await on NodeJS

I think my understanding of it might be affected by my experience with .NET's async/await, so I'd like some code example:

I'm trying to make a express controller wait 5 seconds before returning the response:

const getUsers = async (ms) => {
  var wait = ms => new Promise(resolve => setTimeout(resolve, ms));

  await wait(ms);
};


export const index = (req, res) => {
  async () => {
    await getUsers(5000);

    res.json([
      {
        id: 1,
        name: 'John Doe',
      },
      { id: 2,
        name: 'Jane Doe',
      },
    ]);
  };
};

This code doesn't work, the browser keeps loading and loading and never shows a thing.

The getUser function I built based on this SO answer, and the controller method, based on my (mistaken) understanding of how it works so I'd like some clarification and correction:

1. when should I use await?

To my understanding, you should use await before an async function call. Is this correct? Also, why can I call await before a non-async function that returns a promise?

2. When should I use async?

To my understanding, you mark a function as an async one so that it can be called with the await keyword. Is this correct? Also, [why] do I have to wrap my await getUsers(5000) call in an anonymous async function?

like image 268
Christopher Francisco Avatar asked Jun 13 '17 04:06

Christopher Francisco


People also ask

How do you explain async await?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

How use async await in Node JS example?

With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise.

What is difference between promise and async await in Node JS?

1. Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future. Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously.

Can you explain why we use async await?

They keyword async is used to make a function asynchronous. The await keyword will ask the execution to wait until the defined task gets executed. It allows the use of await Keyword inside the functions with async keyword. Using await in any other way will cause a syntax error.


1 Answers

To clear a few doubts -

  1. You can use await with any function which returns a promise. The function you're awaiting doesn't need to be async necessarily.
  2. You should use async functions when you want to use the await keyword inside that function. If you're not gonna be using the await keyword inside a function then you don't need to make that function async.
  3. async functions by default return a promise. That is the reason that you're able to await async functions.

From MDN -

When an async function is called, it returns a Promise.

As far as your code is concerned, it could be written like this -

const getUsers = (ms) => { // No need to make this async
    return new Promise(resolve => setTimeout(resolve, ms));
};

// this function is async as we need to use await inside it
export const index = async (req, res) => {
    await getUsers(5000);

    res.json([
      {
        id: 1,
        name: 'John Doe',
      },
      { id: 2,
        name: 'Jane Doe',
      },
    ]);
};
like image 150
Jyotman Singh Avatar answered Oct 06 '22 23:10

Jyotman Singh