JavaScript 치트시트
10. 비동기 처리
10.1 콜백 함수
function fetchData(callback) {
setTimeout(() => {
callback('데이터 로드 완료');
}, 1000);
}
fetchData(message => console.log(message));
10.2 Promise (then, catch, finally)
const promise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
success ? resolve('성공') : reject('실패');
}, 1000);
});
promise
.then(result => console.log('결과:', result))
.catch(error => console.error('에러:', error))
.finally(() => console.log('완료'));
10.3 async/await
async function getData() {
try {
const result = await promise;
console.log('결과:', result);
} catch (e) {
console.error('에러:', e);
} finally {
console.log('완료');
}
}
getData();
10.4 fetch API
async function fetchUser() {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
console.log(data);
}
fetchUser();
10.5 setTimeout, setInterval
setTimeout(() => console.log('1초 후 실행'), 1000);
let count = 0;
const intervalId = setInterval(() => {
console.log('반복 실행', ++count);
if (count === 3) clearInterval(intervalId);
}, 1000);