const promise = new Promise((resolve, reject) => {
// 성공: resolve(data)
// 실패: reject(error)
});
대기 (Pending)
→ 아직 작업이 완료되지 않은 상태
성공 (Fulfilled)
→ resolve()가 호출된 상태
실패 (Rejected)
→ reject()가 호출된 상태
const promise = new Promise((resolve, reject) => {
if (성공조건) {
resolve("성공 결과");
} else {
reject("에러 메시지");
}
});
promise
.then((result) => { // 성공 시 실행
console.log("성공:", result);
})
.catch((error) => { // 실패 시 실행
console.error("실패:", error);
});
const promise = new Promise(() => {
setTimeout(() => {
console.log("hi");
}, 3000);
});
console.log(promise);
resolve나 reject를 호출하지 않았기 때문에
→ 상태는 계속 Pending
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("hi");
resolve();
}, 3000);
});
setTimeout(() => {
console.log(promise);
}, 3000);
PromiseResult가 undefined인 이유
→ resolve에 전달한 값이 없기 때문
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("hi");
resolve("hello");
}, 3000);
});
resolve("hello") → PromiseResult는 "hello"
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("hi");
reject("reject");
}, 3000);
});
reject 호출 시 → 상태는 Rejected
Promise를 더 깔끔하게 사용하기 위한 문법이다.
async function 함수이름() {
const result = await Promise객체;
console.log(result);
}
async 함수는 항상 Promise를 반환한다.
async function test() {
return {
name: "gildong",
id: "hong"
};
}
console.log(test());
출력 결과는 Promise 객체
async function test() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: "gildong",
id: "hong"
});
}, 2000);
});
}
console.log(test());
async function run() {
const result = await test();
console.log(result);
}
run();
await는 Promise가 완료될 때까지 기다렸다가
resolve 값만 가져온다.
이벤트가 발생하면 DOM 트리를 따라 전파된다.
이 과정을 이벤트 전파(Event Propagation) 라고 한다.
흐름:
document → html → body → ... → 이벤트 대상
흐름:
이벤트 대상 → 부모 → body → html → document
이벤트가 상위 요소로 전달되는 것을 막는다.
element.addEventListener("click", function(event) {
event.stopPropagation();
});
기본 동작을 막는다.
예: 링크 클릭 시 이동 방지
element.addEventListener("click", function(event) {
event.preventDefault();
});


위의 코드는 "resolve, reject"를 받지 않은 상태이기 때문에 콘솔에서 현재 상태가 계속 pending으로 되어 있는것을 알 수 있다.










아래와 같이 호출 함수 또한 async/await 함수로 바꾸어 적어보면 시간을 기다리고 바로 결과값을 출력하는 것을 볼 수 있다.





