◼ async / await
비동기 코드를 처리하기 위한 문법이며, 가독성을 높이고, 비동기코드를 동기적으로 처리할 수 있도록, ECMAScript 2017(ES8)에 만들어 졌다.
async 함수 | await 표현식 |
Promise 객체와 동일한 상태와 성공여부를 가진 promise 객체를 return 한다. |
async 함수 내에서만 사용 |
await 키워드를 사용하여 다른 async 함수나 Promise가 완료될 때까지 기다릴 수 있다 |
await 키워드를 사용하면 promise가 처리될 때까지 코드의 실행을 일시 중단하고, promise가 이행되면 그 결과를 반환한다 |
비동기성을 유지하면서 코드를 동기적으로 작성한다 |
실행예시
async function fetchData() { // async 키워드 선언
try {
// fetch 함수가 성공 여부를 나타내는 Promise를 반환하고,
// 이를 await 키워드를 사용하여 기다린 후에 response 받아오고 리턴해 준다
const response = await fetch('https://json.aaaa.com/posts/1');
// 응답을 JSON 형식으로 파싱
const data = await response.json();
console.log(data); // 데이터를 콘솔에 출력
} catch (error) {
console.error('Error:', error); // 에러가 발생하면 콘솔에 에러 메시지 출력
}
}
fetchData(); // fetchData 함수 호출
Promise 객체 값을 리턴
Promise 객체 이외의 값을 리턴
- 객체 이외에 숫자나 문자열, 일반 객체 등을 리턴하는 경우,
fulfilled 상태이면서, 리턴된 값을 작업 성공 결과로 가진 Promise 객체
1.
async function fetchAndPrint() {
return 3;
}
fetchAndPrint();
2.
async function fetchAndPrint() {
const member = {
name: 'Jerry',
email: 'jerry@codeitmall.kr',
department: 'sales',
};
return member;
}
fetchAndPrint();
아무 값도 return 않을 경우
- 아무값도 리턴하지 않을 때는 undefined를 리턴한 것을 간주한다.
1.
async function fetchAndPrint() {
console.log('Hello Programming!');
}
fetchAndPrint();
2.
async function fetchAndPrint() {
alert('hellow'); // 먼저 뜨고 출력
}
fetchAndPrint();
async 함수 내부 에러 발생
rejected 상태이면서, 해당 에러 객체를 작업 실패 정보로 가진 Promise 객체가 리턴된다
async function fetchAndPrint() {
throw new Error('Fail');
}
fetchAndPrint();
◼ fetch와 async / await 문법 비교
1. promise 문법
fetch("https://json.aaaa.com/users")
.then((response) => response.json())
.then((users) => {
const lastUser = users[users.length - 1];
return lastUser.id;
})
.then((id) => fetch(`https://json.aaaa.com/?userId=${id}`)
.then((response) => response.json())
.then((posts) => {
const lastPost = posts[posts.length - 1];
console.log(lastPost);
});
2. async / await 문법
async function getTheLastPostOfTheLastUser() {
const response = await fetch("https://json.aaaa.com/users");
const lastUser = await response.json();
const id = await lastUser[lastUser.length - 1].id;
const response2 = await fetch(`https://json.aaaa.com/?userId=${id}`);
const posts = await response2.json();
const lastPost = await posts[posts.length - 1];
return lastPost
}
getTheLastPostOfTheLastUser().then((lastPost) => {
console.log(lastPost);
});
◼ catch와 finally 사용하기
async / await에서 catch, finally 사용하는 방식에 대한 예제 코드로 정리해 보았다
fetch함수에서 사용하던 promise 방식과 많이 다른점이 없다.
async function getTheLastPostOfTheLastUser() {
try{ // 실행
const response = await fetch("https://json.aaaa.com/users");
const lastUser = await response.json();
const id = await lastUser[lastUser.length - 1].id;
const response2 = await fetch(`https://json.aaaa.com/userId=${id}`);
const posts = await response2.json();
const lastPost = await posts[posts.length - 1];
console.log(lastPost);
} catch (error) { // 문제시 catch 메소드 실행
console.log(error);
} finally { // 성공여부 상관없이 상시 출력
console.log('END!')
}
}
getTheLastPostOfTheLastUser().then((lastPost) => {
console.log(lastPost);
});
◼ 함수에 사용하는 async
api를 가져올때만이 아닌, 일반 함수와 즉시실행 함수에서도 사용이 가능하다
함수 선언식, 표현식, arrow 예제
// 1) Function Declaration
async function example1(a, b) {
return a + b;
}
// 2-1) Function Expression(Named)
const example2_1= async function add(a, b) {
return a + b;
};
// 2-2) Function Expression(Anonymous)
const example2_2 = async function(a, b) {
return a + b;
};
// 3-1) Arrow Function
const example3_1 = async (a, b) => {
return a + b;
};
// 3-2) Arrow Function(shortened)
const example3_2 = async (a, b) => a + b;
즉시실행함수
(async function print(sentence) {
console.log(sentence);
return sentence;
}('I love JavaScript!'));
(async function (a, b) {
return a + b;
}(1, 2));
(async (a, b) => {
return a + b;
})(1, 2);
(async (a, b) => a + b)(1, 2);
◼ 반복문에서 async
반복문에서도 사용이 가능하다
순차적인 작업을 처리할떄는 async가 좋지만, 순서에 상관없는 경우라면 아쉬울 수도 있다
for문
urls라는 파라미터로, 여러 개의 URL들이 있는 배열을 받아서, 순서대로 각 URL에 리퀘스트를 보내고, 그 리스폰스의 내용을 출력하는 함수예제이다.
1. 순차적으로 실행
async function getResponses(urls) {
for(const url of urls){
const response = await fetch(url);
console.log(await response.text());
}
}
2. 정의와 동시에 실행되는 즉시실행 함수 추가
async function fetchUrls(urls){
for(const url of urls){
(async () => { // 추가된 부분!
const response = await fetch(url);
console.log(await response.text());
})(); // 추가된 부분!
}
}
'[노트장] 적으며 정리해 보는 이론 > 웹개발기본' 카테고리의 다른 글
[웹개발기본] Promise (1) | 2024.03.12 |
---|---|
[웹개발기본] Fetch (0) | 2024.03.11 |
[웹개발기본] HEAD Content-Type (0) | 2024.03.11 |
[웹개발기본] Request의 종류 (0) | 2024.03.11 |
[웹개발기본] 직렬화, 역직렬화 : 데이터를 다른 형식으로 (0) | 2024.03.11 |