Understanding async/await on NodeJS

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',
      },
    ]);
};

Leave a Comment