async와 await

1. async 함수

예시

async function f1() {
  return 1; // 값 반환
}
async function f2() {
  return Promise.resolve(1); // 명시적 프로미스 반환
}

f1().then(alert); // 1
f2().then(alert); // 1

2. await

**async** function f() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("완료!"), 1000)
  });
  let result = **await** promise; // 프라미스가 이행될 때까지 기다림 (*)
  
  alert(result); // "완료!"
}

f();

예시

async function showAvatar() {

  // JSON 읽기
  let response = await fetch('/article/promise-chaining/user.json');
  let user = await response.json();

  // github 사용자 정보 읽기
  let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
  let githubUser = await githubResponse.json();

  // 아바타 보여주기
  let img = document.createElement('img');
  img.src = githubUser.avatar_url;
  img.className = "promise-avatar-example";
  document.body.append(img);

  // 3초 대기
  await new Promise((resolve, reject) => setTimeout(resolve, 3000));

  img.remove();

  return githubUser; // 해당 값을 결과값으로 가지는 프로미스를 리턴하게 된다. 
}

showAvatar();