<the ASYNC keyword>

: async function 선언은 이벤트 루프를 통해 비동기적으로 작동하는 함수로, 암시적으로 Promise를 사용하여 결과를 반환한다.

 

// REGULAR function returns a string:
function greet() {
return 'HELLO!!!';
}

// THE ASYNC KEYWORD!
// This function returns a promise.
async function greet() {
	return 'HELLO!!!'; //->resolved with the value of 'HELLO!!!'
}

greet().then((val) => {
	console.log('PROMISE RESOLVED WITH: ', val);
});
PROMISE RESOLVED WITH: HEllO!!!

 

 

- async function의 에러처리

// Equivalent non-async function...
// function add(x, y) {
// 	return new Promise((resolve, reject) => {
// 		if (typeof x !== 'number' || typeof y !== 'number') {
// 			reject('X and Y must be numbers!');
// 		}
// 		resolve(x + y);
// 	});
// }


async function add(x, y) {
	if (typeof x !== 'number' || typeof y !== 'number') {
		throw 'X and Y must be numbers!';
	}
	return x + y;
}


add(6, 7)
	.then((val) => {
		console.log('PROMISE RESOLVED WITH: ', val);
	})
	.catch((err) => {
		console.log('PROMISE REJECTED WITH: ', err);
	});

-> 예상된 에러 하나만 처리 가능

 

 

// ver 1
async function getPlanets() {
	//Invalid URL...
	const res = await axios.get('https://swapi.co/api/planeklsajdalksts/');
	console.log(res.data);
}

getPlanets().catch((err) => {
	console.log('IN CATCH!!!');
	console.log(err);
});

// ver 2
async function getPlanets() {
	try {
		const res = await axios.get('https://swapi.co/api/planeklsajdalksts/');
		console.log(res.data);
	} catch (e) {
		console.log('IN CATCH!', e);
	}
}
getPlanets();

-> 코드실행시 발생하는 모든 예외를 처리 가능

 

 

 

 

<the AWAIT keyword>

: async 함수에는 await식이 포함.

async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 후, async 함수의 실행을 다시 시작하고 완료후 값을 반환.

 

async function getPlanets() {
	const res = await axios.get('https://swapi.co/api/planets/');
	console.log(res.data); //only runs once the previous line is complete (the axios promise is resolved)
}

getPlanets();



// Without async/await...

// function getPlanets() {
// 	return axios.get('https://swapi.co/api/planets/');
// }

// getPlanets().then((res) => {
// 	console.log(res.data);
// });

'javascript' 카테고리의 다른 글

JavaScript/ Parallel vs Sequential & Promise.all  (0) 2020.04.15
JavaScript/ AXIOS  (0) 2020.04.14
JavaScript/ Fetch API  (0) 2020.04.14
JavaScript/ AJAX & XML Http Request  (0) 2020.04.14
JavaScript/ CallBack Hell & Promise!  (0) 2020.04.14