Understanding async/await on NodeJS

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

    Async functions in Javascript

    The async keyword turns a regular JS function declaration into an asynchronous function declaration:

    function syncFunc {// dostuff}
    async function asyncFunc {// dostuff} // the async keyword is placed before the function keyword
    

    An async function returns a Promise:

    • When the async function returns a value, the Promise will be resolved with the returned value.
    • When the async function throws an exception or some value, the Promise will be rejected with the thrown value.

    Inside an async function you can use the await keyword. await placed before a promise causes the async function to pause until the promise is settled (either rejected or fulfilled)

    • . When the promise fullfills The value of the await expression is the value of the fullfilled promise.
    • When the promise is rejected the await expression throws the rejected value.

    Example:

    function makePromise(x) { 
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(x);
          }, 1000);
        });
      }
      
      async function asyncFunc() {
        var x = await makePromise(1); // the function is paused here until the promise is fulfilled
        console.log(x); // logs 1
        return x;
      }
      
      const returnedProm = asyncFunc(); // the async func returns a promise
    
    
      returnedProm.then((x) => console.log(x));
      // This promise is fulfilled with the return value from the async func, so this logs 1

    When to use asynchronous functions:

    Async functions are a useful tool when you have multiple asynchronous actions (implemented as promises) which depend on each other. For example when your second promise needs data that your first promise will provide. You now can conveniently use the await keyword to first receive the data in promise 1, and then pass this data as an argument to promise 2.

    In other words, async function can via the await keyword make asynchronous programming behave like synchronous programming. As a consequence your applications are easier to understand.

提交回复
热议问题