javascript/기본

javascript Promise Async/Await

IT-개발자 2023. 2. 14. 02:35
반응형

자바스크립트에서 비동기 처리를 위한 콜백함수 사용 시 콜백 지옥을 해결할 수 있는 것이 Promise입니다. Async/Await 는 비동기 처리 문법으로 가장 최근에 나온 문법으로 ES8에 해당하며 Promise를 쉽게 사용할 수 있도록 합니다.

 

  • Async는 함수 앞에 선언되며 Async의 결과는 Promise 객체로 return 됩니다.
  • Await는 Async와 쌍을 이루어 사용하여 Await를 사용하면 함수앞에 Async를 작성해야 한다.
  • Promise와 차이점은 기존 함수에 Async를 작성하는 것처럼 구성되어 간결하다.
  • 가장 큰 차이점은 비동기 처리에 사용되는 문법이지만 코드 실행을 동기적으로 코딩을 할 수 있는것 입니다.

실무에서 많이 사용되니 실습을 통해 살펴보도록 하겠습니다.

 

실습:

async 를 함수 test앞에 작성하고 console.log("result_promise "+result_promise); 를 확인하면 Object 는 Promise 임을 알 수 있습니다. 그리고 then 함수는 Promise에서 사용하는 것으로 async 는 Promise 객체를 반환하는 것을 확인할 수 있습니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script>
        async function test(value) {
           return (value+1);
        }
       
        let result_promise = test();
        console.log("result_promise "+result_promise);
       
        test(1).then((value) => console.log("value:"+value));
    </script>
</body></html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script>
        const f = async (value) => {
            return value+1;
        }

        f(3).then((value) => console.log(value))
    </script>
</body></html>

실습: 

await 는 비동기 처리에서 동기 형태의 로직을 사용할 수 있게 하는 것으로 해당 로직을 기다리게 합니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script>
        const timer = () => {
            return new Promise(resolve => setTimeout(resolve, 1000));
          };
         
          async function wait(){
            await timer();
            return "wait";
          };


         async function test(){
            const waitstr = awaitwait();
            return waitstr;
         }
         
         test().then(console.log)
    </script>
</body></html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <script>
        const timer = () => {
            return new Promise(resolve => setTimeout(resolve, 1000));
          };
         
          async function wait(){
            timer();
            return "wait";
          };


         async function test(){
            const waitstr = wait();
            return waitstr;
         }
         
         test().then(console.log)
    </script>
</body></html>

자료가 마음에 드셨다면 자주 찾아주세요^^ 글 올리는데 힘이됩니다.

반응형