관리 메뉴

KorSA

[ JavaScript ES 6 ] async, await 본문

Knowledge Wiki/Javascript

[ JavaScript ES 6 ] async, await

Praiv. 2021. 12. 17. 17:55
320x100

1. ES8부터 Promise 대신 async/await 문법 사용 가능
    async를 function 앞에 붙이면 함수 실행 후에 Promise 오브젝트가 남음
    But, async는 Promise와 달리 기본적으로 reject 처리가 안됨.
    정 하고 싶으면 Promise.reject()를 리턴해야 함.

async function add(){
	return 1 + 1;
}

add().then(function(res){
	console.log(res);
})


2. await은 then() 대신 사용 가능

var pro = new Promise(function(resolve, reject){
	resolve();
});

var result = await pro; // Promise가 끝날 때까지 기다려!
console.log(result);

// await 안쓰고 Promise 패턴일 때 코드 -> 길다..
pro.then(function(result){
	console.log(result);
});


3. await은 Promise 실패시 에러나고 멈춤 -> 그래서 방지하려면 try{} catch{} 사용

try{
	var result = await pro; // Promise가 끝날 때까지 기다려!
	console.log(result);
}
catch{
	console.log('fail');
}
728x90
728x90
Comments