본문 바로가기

코딩도 합니다/JS

[자바스크립트 js] async / await / try catch문 / finally문 / 비동기 실행



  async / await

  • promisechaining을 개발자가 더 편하게 작성할 수 있도록 하고, 코드의 가독성을 높이기 위한 구문 .
  • promise 객체를 사용할 때 then 메소드 등을 사용하지 않고도 마치 동기 실행 코드처럼 코드를 훨씬 더 간단하고 편하게 작성할 수 있다.
  • 그러나 async / await 구문이 동기 실행 코드처럼 생겼다고 해도 그 속에는 promise 객체가 존재한다는 것을 유의할 것.
  • async 함수 안의 코드가 실행되다가 await을 만나면, 일단 await 뒤의 코드가 실행되고, 코드의 실행 흐름이 async 함수 바깥으로 나가서 나머지 코드를 다 실행한다.
  • async
    - asynchronous(비동기)의 줄임말.
    - async함수는 항상 promise 객체를 리턴한다.
  • await
    - promise 객체를 리턴하는 코드 앞에 붙어 있다.
    - 해당 코드를 실행하고 그 코드가 리턴하는 promise 객체가 fulfilled / rejected 상태가 될 때까지 기다려준다.
    - 작업성공결과 / 작업실패결과를 리턴한다. async 함수 안에서만 사용할 수 있는 키워드.
// fetch('https://tooktak.com/doti')
//    .then((response) => response.text())
//    .then((result) => { console.log(result); });


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

fetchAndPrint();

 

 

 

  await을 만나는 순간 함수 바깥의 코드를 실행하고 돌아온다.

코드에 await이 존재하면 코드가 보이는 순서대로 실행되는 것이 아니라는 걸 이해하자.

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

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

 

 

 

 

  try catch문

rejected 상태가 되는 것을 대비할 수 있다.

async function fetchAndPrint() {
	try {
    	const response = await fetch('https://tooktak.commm/doit');
    	const result = await response.text();
		console.log(result);
	} catch (error) {    // error 파라미터로 작업실패정보가 입력된다.
    	console.log(error);
    }
}


fetchAndPrint();

 

 

 

 

 

  finally문

어떤 상태에서든 항상 실행된다. (아래 코드에서 '끝'은 어떤 상황에서든 출력된다.)

async function fetchAndPrint() {
	try {
    	const response = await fetch('https://tooktak.commm/doit');
    	const result = await response.text();
		console.log(result);
	} catch (error) {    // error 파라미터로 작업실패정보가 입력된다.
    	console.log(error);
    } finally {
    	console.log('끝');
    }
}


fetchAndPrint();

 

 

 

 

 

  async 함수는 promise 객체를 리턴한다.

async function fetchAndPrint() {
	return 5;
}

fetchAndPrint();

// 결과
// promis {<fulfilled>: 5}

 

 

 

 

 

 

  아무 값도 리턴하지 않은 경우

이 경우에는 fulfilled 상태이면서, undefined를 작업 성공 결과로 가진 promise 객체가 리턴된다.

async function fetchAndPrint() {
	console.log('뚝딱 할 수 있다');
}


fetchAndPrint();

 

 

 

 

  async 함수 내부에서 에러가 발생했을 때

rejected 상태이면서, 해당 에러 객체를 작업 실패 정보로 가진 promise 객체가 리턴된다.

 

 

 

 

 

  async 함수 안의 async 함수

함수 선언식이 아니라 함수 표현식으로 만들 수 있다.

const tooktak = async function (doordie) {
...
}

 

728x90