본문 바로가기

JavaScript/Web Development

[JavaScript] async/ await

다음 코드를 실행하면,

 

// fetch('https://jsonplaceholder.typicode.com/users')
//  .then((response) => response.text())
//  .then((result) => { console.log(result); });

async function fetchAndPrint() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const result = await response.text()
  console.log(result);
}

fetchAndPrint();

 

 

위의 주석처리한 promise chain 코드를 실행했을 때와 똑같이 response 가 잘 출력됨.

 

[async] 

asynchronous 의 줄임말로, 비동기를 의미한다. 이는 함수안에 비동기적으로 실행될 부분이 있다는 것을 의미하는데, 아래 코드에서는 await 을 뜻함.

 

[await]

뒤에있는 코드를 실행하고, 그것이 리턴하는 promise 객체가 fulfilled 상태가 될 때까지 기다리고, 이후 작업성공 결과를 리턴함.

async 가 붙어있는 함수 안에, 비동기 실행이 되는 부분이 있다는 뜻은 함수의 코드 중 Promise 객체를 리턴하는 코드가 있다는 것.

그 앞에 await 을 붙여 fulfilled 상태가 될 때까지 기다리는 것.

 

 

promise 객체를 리턴하는 코드 앞에 붙어있으며, 첫번째 await 은 뒤의 코드를 실행하고 그 뒤에 코드 (fetch 함수) 가 리턴하는 promise 객체가 fulfilled 혹은 rejected 가 될 때까지 기다림.

두번째 await 또한 text 메소드가 리턴하는 promise 객체가 fulfilled 상태가 될 때까지 기다리고, fulfilled 상태가 되면 그 작업성공 결과를 리턴함.


 

[async/ await 구문의 실행 원리]

 

1. await 은 async 안에서만 쓸 수 있음.

 

// fetch('https://jsonplaceholder.typicode.com/users')
//  .then((response) => response.text())
//  .then((result) => { console.log(result); });

function fetchAndPrint() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  const result = await response.text()
  console.log(result);
}

fetchAndPrint();

 

function 앞의 async 를 지운 위의 코드를 실행해보면, 

 

 

await 은 async 에서만 유효하다는 에러가 나타난다.

 


2. await 이 있다면 코드는 보이는대로 실행되지 않음.

 

아래 코드를 실행하면, console.log(number); 순서대로 코드가 실행되는데, 

 

// fetch('https://jsonplaceholder.typicode.com/users')
//  .then((response) => response.text())
//  .then((result) => { console.log(result); });

async function fetchAndPrint() {
  console.log(2);
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  console.log(7);
  const result = await response.text()
  console.log(result);
}

console.log(1);
fetchAndPrint();
console.log(3);
console.log(4);
console.log(5);
console.log(6);

 

이를 순서대로 살펴보면, 

 

(1) fetchAndPrint() 함수를 선언

(2) console.log(1); 실행 -> 숫자 1 출력

(3) 아래의 fetchAndPrint(); 실행

(4) fetchAndPrint() 함수 안에서 console.log(2); 실행 -> 숫자 2 출력

(5) 첫번째 await 을 만나서 뒤의 코드를 실행

(6) 다시 아래의 fetchAndPrint(); 실행 흐름으로 감

(7) console.log(3); , console.log(4); , console.log(5); , console.log(6); 실행 -> 숫자 3, 4, 5, 6 출력

(8) await 문 뒤에 있던 promise 객체가 fulfilled 상태가 될 때까지 기다림

(9) fulfilled 상태가 되면, 작업 성공 결과인 response 객체를 리턴

(10) console.log(7); 출력

(11) 두 번째 await 코드 실행, 다시 흐름은 아래의 fetchAndPrint(); 로 넘어감

(12) 더이상 실행할 코드가 없으므로 text 객체가 리턴하는 promise 객체가 fulfilled 상태가 될 때까지 넘어감.

 

여기에서 undefiend 값은, 마지막 6 을 출력하는 console.log 가 아무런 리턴값이 없어 출력됨.

await 이 있다면, 코드가 보이는 순서대로 실행되는 것이 아니라는 것을 기억해야함