Understanding async/await on NodeJS

前端 未结 4 2073
醉话见心
醉话见心 2020-11-30 09:33

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

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 09:35

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

提交回复
热议问题