[JavaScript] async await공부방2023. 1. 21. 15:19
Table of Contents
728x90
728x90
Promise사용 시 불편한 점들
1. then()을 연속적으로 호출하여 문제 발생 시 혼란을 겪을 수 있다.
2. 복잡한 구조의 비동기처리 코드 작성 시 코드의 가독성이 저하된다.
3. 동기코드와 비동기코드가 섞여있을 때 예외처리 하기가 난해하다.
async / await
Promise의 불편한 점들을 해결하기 위해 ES7에서 async/await가 추가되었다.
async function f() {
return 1;
}
f().then(alert); // 1
async는 function 앞에 위치하며, async가 붙은 함수는 항상 Promise를 반환한다.
Promise객체를 생성하지 않더라도 Promise 객체가 리턴되는 것에 주의하자.
await는 async함수 내부에서만 동작한다.
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("완료!"), 1000)
});
let result = await promise; // 프라미스가 이행될 때까지 기다림 (*)
alert(result); // "완료!"
}
f();
await는 Promise가 처리될 때 까지 함수 실행을 기다리게 만드는 특징이 있다.
비동기 작업의 결과값을 얻을 때 까지 대기했다가 그 결과값과 함께 실행이 재개된다.
Promise가 처리되길 기다리는 동안에 다른 일(다른 스크립트 실행 및 이벤트 처리 등)을 할 수 있기 때문에 효율적이다.
프라미스 체이닝을 async/await로 변경하기
아래의 프라미스체이닝 예시를 async/await를 사용해 다시 작성해보자.
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => new Promise(function(resolve, reject) { // (*)
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser); // (**)
}, 3000);
}))
.then(githubUser => alert(`${githubUser.name}의 이미지를 성공적으로 출력하였습니다.`));
then 호출을 await로 변경하고, function앞에 async를 붙여 await를 사용할 수 있게 하면 된다.
async function showAvatar() {
// JSON 읽기
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
// github 사용자 정보 읽기
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
// 아바타 보여주기
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
// 3초 대기
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
showAvatar();
예외처리
그저 try/catch로 일관되게 예외처리를 할 수 있다.
function getTitle(){
const response = fetch("https://jsonplaceholder.typicode.com/posts");
return response.then(res => res.json());
}
async function exec(){
var text;
try {
text = await getTitle();
console.log(text[0].title);
}
catch(error){
console.log(error);
}
}
exec();
728x90
300x250
@mag1c :: 꾸준히 재밌게
2023.04 ~ 백엔드 개발자의 기록
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!