비동기 처리 - 1. 비동기와 콜백 글 보러 가기

비동기 처리 - 2. Promise 글 보러 가기

비동기 처리 - 3. Promise Chainig | Error Handling 글 보러 가기

비동기 처리 - 4. Promise API 글 보러 가기

비동기 처리 - 5. microtask 글 보러 가기

 


 

개요

 


 

1. async, await 개요

의미

프로미스 문을 보다 가독성 있게 만들어주는 도구

 

특징
  • function 앞에 async 사용
  • async 키워드가 반드시 있어야 함수 내에서 await 사용 가능 : async + await 은 짝꿍!
  • await = Promise ~ .then 이라고 볼 수 있음

 

예시 코드
async function f() {
  let promise = new Promise((resolve, reject) => {  //async 함수 내에 프로미스도 넣을 수 있음
    setTimeout(() => resolve("완료!"), 1000)
  });
  let result = await promise; // 프라미스가 이행될 때까지 기다림 (*)
  alert(result); // "완료!"
}
f();

// 프로젝트에 적용 
async detect(imageData) {
  if (!this._detector) {
      this._detector = await this._createDetector();
      console.log("model loading success!, detector: ", this._detector);
  }
  this._result = await this._detector.estimateFaces(imageData);
  console.log('this._result: ', this._result);
//... 중략
}

 

에러 핸들링 : try ~ catch 문과 함께 사용 가능!
async function f() {
  try {
    let response = await fetch('http://유효하지-않은-주소');
    let user = await response.json();
  } catch(err) {
    // fetch와 response.json에서 발행한 에러 모두를 여기서 잡습니다.
    alert(err);
  }
}

f();

 


 

2. 프로미스 함수와 비교

프로미스
function showAvatar(githubUser) {
  return new Promise(function(resolve, reject) {
    let img = document.createElement('img');
    img.src = githubUser.avatar_url;
    img.className = "promise-avatar-example";
    document.body.append(img);
    setTimeout(() => {
      img.remove();
      resolve(githubUser);
    }, 3000);
  });
}

 

async, await
async function showAvatar() {
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));
	// await은 Promise 및 Promise.all과 함께 사용 가능
  img.remove();
  return githubUser;
}
  • .catch 대신 try ~ catch 문 사용 가능 → 가독성 향상
  • 주의할 점 : async, await은 프로미스 기반임

 


 

3. 비동기 관련 추가로 공부하면 좋을 주제 

+ Recent posts