23.08.30
Promise : JavaScript에서 비동기 처리에 사용되는 객체, 뜻 그대로 '약속' 이라는 의미 !
즉, 내용은 실행 되었으나 제대로 처리가 된 후에 데이터를 넘겨주고 아니면 오류를 줄 것이라는 약속이다.
Promise의 3가지 상태
cosnt fetchData = () => {
// Promise 객체 생성
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Hello, Promise with arrow function!";
if (data) {
resolve(data);
} else {
reject("Error: Data not available.");
}
}, 2000);
});
}
fetchData()
.then(result => {
console.log(result); // 작업이 성공했을 때 출력
})
.catch(error => {
console.error(error); // 작업이 실패했을 때 출력
});
Async - Await : 기존에 존재하는 Promise를 조금 더 간편하게 사용 할 수 있도록 도와주며 동기적으로 실행되는 것 처럼 보이게 하는 문법 => 즉, Promise의 Syntatic sugar
Q. 그렇다면 여기서 Syntatic sugar란?
A. 문법적 기능은 그대로인데(같은데) 사람이 사용하기 편하게 제공되는 프로그래밍 문법을 의미한다. 기존에 존재하던 문법을 함수 등으로 감싸서 조금 더 간편하게 바꿔서 사용할 수 있도록 도와준다.
Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain.
=> awiat은 Promise의 then을 표현하는 또 다른 문법
즉, Promise가 resolve하거나 reject할 때 까지 async Call 내부에서 기다렸다가 결과에 오류가 없으면 그 때 result를 정상적으로 출력해준다.
const fetchData = () => {
// Promise 객체 생성
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Hello, async-await with arrow function!";
if (data) {
resolve(data);
} else {
reject("Error: Data not available.");
}
}, 2000);
});
}
// 매개변수 앞에 async를 적고, Promise 함수 실행 앞에 await을 적음
const main = async () => {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}
main();