async/await
promise기반으로 동작
promise의 then/catch/finally 후속 처리 메서드에 콜백 함수를 전달하여 비동기 처리 결과를 후속 처리 필요 없이
동기처럼 promise를 사용하여 처리 결과를 반환
1. async
async는 함수 앞에 붙여 해당 함수를 비동기 함수로 만든다.
항상 Promise 객체를 반환하며, 반환된 값이 프로미스가 아닌 경우 자동으로 Promise.resolve()로 감싸져 반환
async function fetchData() {
return "데이터";
}
fetchData().then(data => console.log(data)); // 출력: "데이터"
2. await
await 키워드는 async 함수 내부에서만 사용
await는 Promise가 처리될 때까지 기다린 후, 해당 Promise의 결과를 반환
비동기 작업이 끝날 때까지 기다리며, try...catch 구문을 사용하여 에러를 처리
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("에러 발생:", error);
}
}
getData();
fetch 함수는 Promise를 반환하는데, await를 사용하면 fetch가 완료될 때까지 기다린 후 그 결과를 response에 저장
에러가 발생하면 catch 블록이 실행
3. async/await의 장점
- 코드 가독성 향상: async/await는 코드의 가독성을 높여, 비동기 작업을 순차적으로 처리할 때 코드가 더 직관적이다.
- 에러 처리 용이성: try...catch 구문으로 에러 처리가 가능해 에러 핸들링이 간단해진다.
// Promise 사용
function getDataPromise() {
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("에러 발생:", error));
}
// async/await 사용
async function getDataAsync() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("에러 발생:", error);
}
}
'JS' 카테고리의 다른 글
| 변수 var / let / const (0) | 2024.11.12 |
|---|---|
| promise : 비동기 작업 여부 (0) | 2024.10.31 |
| 컨텍스트를 가리키는 키워드 this (0) | 2024.10.30 |
| Math : 표준 빌트인 객체 (0) | 2024.10.24 |
| 화살표 함수 (0) | 2024.10.17 |