JavaScript

[Javascript] Async, Await

prefer2 2021. 11. 1. 17:50

 

promise를 쓰면 콜백헬에서는 벗어날 수 있지만 연속되는 then의 사용으로 가독성이 떨어진다. async와 await은 이러한 promise를 조금 더 읽기 쉽고 사용하기 쉽도록 만들어진 문법이다. 

 

사용방법

async function 함수명() {
  await 비동기처리메서드();
}

함수 앞에 async를 붙이면 해당 함수는 반드시 프라미스를 반환한다. 프라미스가 아닌 값을 반환하더라도 이행 상태의 프라미스(resolved promise)로 값을 감싸 이행된 프라미스가 반환되도록 한다.

자바스크립트는 await 키워드를 만나면 프라미스가 처리(settled)될 때까지 기다린다. 결과는 그 이후 반환된다. 프라미스가 처리되길 기다리는 동안 엔진이 다른 일(다른 스크립트를 실행, 이벤트 처리 등)을 할 수 있기 때문에, CPU 리소스가 낭비되지 않는다. await은 async 함수 내에서만 동작한다.

 

예시

function tictok(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function process(sec) {
  console.log('Hello World!');
  await tictok(sec); // 2초
  console.log('this is how async-await works');
}

process(2000);

 

promise를 async/await으로 전환

promise ver

const whereAmI = function(country){
  const res = fetch(`https://restcountries.com/v2/name/${country}`)
  .then(res=>res.json())
  .then(data=>{
    console.log(data[0]);
  })
}

whereAmI('korea');

async/await ver

const whereAmI = async function(country){
   const res = await fetch(`https://restcountries.com/v2/name/${country}`);
   const data = await res.json();
   console.log(data[0]);
}

whereAmI('korea');

 

예외 처리

await가 던진 에러는 throw가 던진 에러를 잡을 때처럼 try..catch를 사용해 잡을 수 있다.

async function f() {

  try {
    let response = await fetch('http://유효하지-않은-주소');
  } catch(err) {
    alert(err); // TypeError: failed to fetch
  }
}

f();

 

참고

https://ko.javascript.info/async-await

 

async와 await

 

ko.javascript.info

 

반응형

'JavaScript' 카테고리의 다른 글

웹팩(webpack) 알러지 치료하기 - 1  (0) 2022.02.27
[javaScript] export와 export default의 차이점  (0) 2021.11.30
[Javascript] Promise  (0) 2021.10.27
[Javascript] Object.create  (0) 2021.10.25
[Javascript] 상속(Inheritance)  (0) 2021.10.19