async/await

SUN·2023년 6월 7일

JS 함수

목록 보기
7/8

프로미스 객체를 간단하게 다룰 수 있는 문법

1. 기본 문법

  • 기존 fetch 함수 코드
fetch ('https://jsonplaceholder.typicode.com/users')
	.then((response) => response.text())
    .then((result) => { console.log(result); });
  • async/await 코드
async function fetchfunc () {
	const response = await fetch ('https://jsonplaceholder.typicode.com/users');
    const result = await response.text();
    console.log(result)
}

fetchfunc()

await는 프로미스 객체를 리턴하는 코드 앞에 붙는다.

await : 뒤 코드가 실행되고 리턴하는 프로미스 객체를 기다린다. ( fulfilled나 rejected 상태까지 기다리고 리스폰스 객체를 리턴) - async 안에서만 활용

실행원리

async function fetchfunc () {
	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)
fetchfunc()
console.log(3)
console.log(4)
console.log(5)
console.log(6)

위 코드를 실행하면 1부터 6까지 순서대로 나타난다.

1 -> fetchfunc() 내부의 2 -> 첫번째 await에서 뒤의 코드를 호출한다. 그 동안 함수 밖으로 나와 그 뒤의 console을 실행한다. 호출이 완료되어 fulfilled 상태가 되면 7이 찍히고 두번째 await의 코드를 호출한다. 그리고 함수 밖으로 나가지만 실행할 코드가 없어 fulfilled 상태를 기다린다.

profile
안녕하세요!

0개의 댓글