Understanding async/await on NodeJS

前端 未结 4 2085
醉话见心
醉话见心 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:46

    async await are just syntactic sugar for promises.

    you use them like you use promises when you want your code to run on complete of a function.

    async function asyncOperation(callback) {
        const response = await asyncStep1();
        return await asyncStep2(response);
    }
    

    is the exact thing if you used promises land syntax:

    function asyncOperation() {
      return asyncStep1(...)
        .then(asyncStep2(...));
    }
    

    The new async/await syntax allows you to still use Promises, but it eliminates the need for providing a callback to the chained then() methods.

    The callback is instead returned directly from the asynchronous function, just as if it were a synchronous blocking function.

    let value = await myPromisifiedFunction(); 
    

    When you are planning to use await in your function you should mark your function with async keyword (like in c#)

    You don't have to create your getUsers as anonymous function.

提交回复
热议问题