이벤트(비동기 작업 완료)가 발생할 때마다 호출되는 함수
function downloadFile(url, callback) {
console.log("Downloading file from", url);
// 가상의 다운로드 완료 후 호출
setTimeout(() => {
console.log("Download complete.");
callback(); // 여기서 콜백 실행
}, 2000);
}
downloadFile("https://example.com", function () {
console.log("After download: processing file...");
});
createAudioFileAsync(audioSettings).then(successCallback, failureCallback);
//=====================
const promise = createAudioFileAsync(audioSettings);
promise.then(successCallback, failureCallback);
콜백은 JavaScript Event Loop가 현재 실행중인 콜 스택을 완료하기 이전에는 절대 호출되지 않음
비동기 작업이 성공하거나 실패한 뒤에 then() 을 이용하여 추가한 콜백도 같음
then()을 여러번 사용하여 여러개의 콜백을 추가 할 수 있음
- 각각의 콜백은 주어진 순서대로 하나 하나 실행되게 됨
두 개 이상의 비동기 작업을 순차적으로 실행해야 하는 상황
- 순차적으로 각각의 작업이 이전 단계 비동기 작업이 성공하고 나서 그 결과값을 이용하여 다음 비동기 작업을 실행해야 하는 경우
- promise chain을 이용하여 해결
Promise는 다음 중 하나의 상태를 가짐
- 대기(pending): 이행하지도, 거부하지도 않은 초기 상태
- 이행(fulfilled): 연산이 성공적으로 완료
- 거부(rejected): 연산이 실패
이행이나 거부될 때, 프로미스의 then 메서드에 의해 대기열(큐)에 추가된 처리기들이 호출
.then() 메서드는 최대 두 개의 인수를 받음
- 첫 번째 인수는 프로미스의 이행된 경우에 대한 콜백 함수
- 두 번째 인수는 거부된 경우에 대한 콜백 함수
then() 함수는 새로운 promise를 반환
then 에 넘겨지는 인자는 선택적(optional)
.then()에 프로미스 객체를 반환하는 콜백 함수가 없는 경우에도 처리는 체인의 다음 링크까지 계속됨
- 체인은 마지막 .catch()까지 모든 거부 콜백 함수를 안전하게 생략할 수 있음
doSomething()
.then(function (result) {
return doSomethingElse(result);
})
.then(function (newResult) {
return doThirdThing(newResult);
})
.then(function (finalResult) {
console.log("Got the final result: " + finalResult);
})
.catch(failureCallback) // then(null, failureCallback) 의 축약
;
// ===================================
doSomething()
.then((result) => doSomethingElse(result))
.then((newResult) => doThirdThing(newResult))
.then((finalResult) => {
console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);
function fetchData1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // 이걸 false로 바꾸면 에러 처리됨
if (success) {
resolve("데이터 가져오기 성공!");
} else {
reject("실패했어요!");
}
}, 2000);
});
}
function fetchData2() {
const promise = new Promise((resolve, reject) => {
console.log("데이터 가져오는 중...");
setTimeout(() => {
const success = true;
if (success) {
resolve("✅ 데이터 가져오기 성공");
} else {
reject("❌ 데이터 가져오기 실패");
}
}, 2000);
});
return promise; // <- Promise 객체 반환
}
fetchData1()
.then((result) => {
console.log("성공:", result);
})
.catch((error) => {
console.error("실패:", error);
});
const myPromise = fetchData2(); // 여기서 아직 결과 없음 (대기 상태)
myPromise
.then((result) => {
console.log("받은 결과:", result);
})
.catch((err) => {
console.error("에러 발생:", err);
});
async function 함수이름() {
const result = await 비동기함수(); // 끝날 때까지 기다림
}
async function getUser() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users/1");
const user = await response.json(); // JSON 파싱도 await 필요
console.log("사용자 이름:", user.name);
} catch (err) {
console.error("에러 발생:", err);
}
}
getUser();