ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Async Await
    JavaScript 2021. 12. 13. 08:58

    자바스크립트의 Async...await 문법의 개념과 사용방법을 정리하였습니다.



    < Introduction >

    The async...await syntax allows us to write asynchronous code that reads similarly to traditional synchronous, imperative programs.

    Its functionaility is completely same as Promises, but async...await powerfully improves the readability and scalability of our code.

     

    Example : callback function(traditional) VS Promises VS async...await

    const fs = require('fs');
    const promisifiedReadfile = require('./promisifiedReadfile');
          
    // Here we use fs.readfile() and callback functions:
    fs.readFile('./file.txt', 'utf-8', (err, data) => {
      if (err) throw err;
      let firstSentence = data;
      fs.readFile('./file2.txt',  'utf-8', (err, data) => {
        if (err) throw err;
        let secondSentence = data;
        console.log(firstSentence, secondSentence);
      });
    });
    
    // Here we use native promises with our "promisified" version of readfile:
    let firstSentence;
    promisifiedReadfile('./file.txt', 'utf-8')
      .then((data) => {
        firstSentence = data;
        return promisifiedReadfile('./file2.txt', 'utf-8');
      })
      .then((data) => {
        let secondSentence = data;
        console.log(firstSentence, secondSentence)
      })
      .catch((err) => {console.log(err)});
    
    // Here we use promisifiedReadfile() again but instead of using the native promise .then() syntax, we declare and invoke an async/await function:
    async function readFiles() {
      let firstSentence = await promisifiedReadfile('./file.txt', 'utf-8');
      let secondSentence = await promisifiedReadfile('./file2.txt', 'utf-8');
      console.log(firstSentence, secondSentence);
    }
    
    readFiles();

     

     


    < The async Keyword >

    To write functions that handle asynchronous actions.

     

    < async >
    - async functions always return a promise. This means we can use traditional promise syntax, like .then() and .catch with our async functions.
    - An async function will return in one of three ways:

    • If there’s nothing returned from the function, it will return a promise with a resolved value of undefined.
    • If there’s a non-promise value returned from the function, it will return a promise resolved to that value.
    • If a promise is returned from the function, it will simply return that promise

     

    Example)

    async function fivePromise() { 
      return 5;
    }
    
    // Same
    const fivePromise = async() => {
      return 5;
    }
     
    fivePromise()
    .then(resolvedValue => {
        console.log(resolvedValue);
      })  // Prints 5

     

     


    < The await Operator >

    await is an operator : it returns the resolved value of a promise.
    To do this, await pauses, or halts the execution of async function 

     

    • The await keyword can only be used inside an async function.
    • If the promise is rejected, the await statement throws the rejected value.

     

    Example1)

    // resolve
    async function asyncFuncExample(){
      let resolvedValue = await myPromise();
      console.log(resolvedValue);
    }
    asyncFuncExample(); // Prints: I am resolved now!
    
    // reject
    async function f3() {
      try {
        var z = await Promise.reject(30);
      } catch(e) {
        console.log(e);
      }
    }
    f3(); // Prints: 30

     

    Example2)

    let myPromise = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('Yay, I resolved!')
        }, 1000);
      });
    }
    
    async function noAwait() {
     let value = myPromise();
     console.log(value);
    }
     
    async function yesAwait() {
     let value = await myPromise();
     console.log(value);
    }
     
    noAwait(); // Prints: Promise { <pending> }
    yesAwait(); // Prints: Yay, I resolved!

     

     


    < Handling Dependent Promises >

    The true beauty of async...await is when we have a series of asynchronous actions which depend on one another.

     

    Example)

    // .then() version
    function nativePromiseVersion() {
      returnsFirstPromise()
        .then((firstValue) => {
          console.log(firstValue);
          return returnsSecondPromise(firstValue);
        })
       .then((secondValue) => {
          console.log(secondValue);
        });
    }
    
    // async...await version
    async function asyncAwaitVersion() {
      let firstValue = await returnsFirstPromise();
      console.log(firstValue);
      let secondValue = await returnsSecondPromise(firstValue);
      console.log(secondValue);
    }

    :  the async...await version more closely resembles synchronous code, which helps developers maintain and debug their code.

     

     


    < Handling Errors >

    With async...await, we use try...catch statements for error handling.
    By using this syntax, not only are we able to handle errors in the same way we do with synchronous code, but we can also catch both synchronous and asynchronous errors.

     

    Example)

    async function usingTryCatch() {
     try {
       let resolveValue = await asyncFunction('thing that will fail');
       let secondValue = await secondAsyncFunction(resolveValue);
     } catch (err) {
       // Catches any errors in the try block
       console.log(err);
     }
    }
     
    usingTryCatch();

     

     


    < Handling Independent Promises >

    What if our async function contains multiple promises which are not dependent on the results of one another to execute?

     

    Example)

    async function waiting() {
     const firstValue = await firstAsyncThing();
     const secondValue = await secondAsyncThing();
     console.log(firstValue, secondValue);
    }
     
    async function concurrent() {
     const firstPromise = firstAsyncThing();
     const secondPromise = secondAsyncThing();
    console.log(await firstPromise, await secondPromise);
    }

    - In the waiting() function, we pause our function until the first promise resolves, then we construct the second promise. Once that resolves, we print both resolved values to the console.

    - In our concurrent() function, both promises are constructed without using await. We then await each of their resolutions to print them to the console.

    -> With our concurrent() function, both promises asynchronous operations can be run simultaneously.

     

     


    < Await Promise.all() >

    Promise.all( ) is a good choice if multiple asynchronous tasks are all required, but none must wait for any other before executing.

     

    Example)

    async function asyncPromAll() {
      const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
      for (let i = 0; i<resultArray.length; i++){
        console.log(resultArray[i]); 
      }
    }

     

     

    Reference : Choose the right approach in Asynchronouse Javascript

     

    Choosing the right approach - Learn web development | MDN

    To finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. We'll

    developer.mozilla.org

     

    'JavaScript' 카테고리의 다른 글

    Requests 2  (0) 2021.12.15
    Requests 1  (0) 2021.12.13
    Promise  (0) 2021.12.13
    Asynchronous / Event Loop  (0) 2021.12.12
    Error Handling  (0) 2021.12.11

    댓글

Designed by Tistory.