async 와 await

async/await 구문은 Promise 객체를 다루는 코드(Promise Chaining 코드 등)를 사람들이 좀더 익숙하게 느끼는

동기 실행 스타일의 코드로 작성할 수 있게 해주는 Syntactic sugar이다.

아래는 promise 를 다루는 코드와 async/await 문법을 비교한것이다. 두 결과는 동일하다.

 

Promise

fetch('https://www.google.com')
    .then((response) => response.text())
    .then((result) => {
        console.log('a');
    })
    .catch((error) => {
    	console.log(error);
    })
    .finally(() => {
    	console.log('exit')
    });

 

async 와 await

async function fetchAndPrint() {
  try {
    const response = await fetch('https://www.google.com');
    const result = await response.text();
    console.log('a');
  } catch(error) {
    console.log(error);
  } finally {
    console.log('exit');
  }
}

fetchAndPrint();

 

+ Recent posts