참조 - 캡틴판교
1. pending [대기] - 생성시 상태
const p = new Promise((resolve, reject) => {})
// ex) axios.get() 요청을 보낸상태
new Promise((resolve, reject) => {})
// resolve()
// type1 - base resolve()
new Promise((resolve, reject) => {
resolve()
})
// type2 - return resolve value, then에서 받기
function promise1() {
new Promise((resolve, reject) => {
const data = 100
resolve(data)
})
}
promise1().then((resolvedData) => {
console.log(resolvedData)
})
// type3 - 바로 resolve() 리턴, then에서 받기
const promise2 = Promise.resolve(123);
promise2.then((value) => {
console.log(value);
// expected output: 123
});
// reject()
// type1 - base reject()
new Promise((resolve, reject) => {
reject()
})
// type2 - return reject value, catch에서 받기
function promise3() {
return new Promise((resolve, reject) => {
reject(new Error("Request is failed"));
});
}
promise3().catch((error) => {
console.log(error)
})
// type3 - 바로 reject() 리턴, catch에서 받기
Promise.reject(new Error("fail")).catch(function(error) {
console.log(error); // Stacktrace
});
// handleSuccess, handleError
// type3-1 - catch대신 사용할 수 있는 문법 >> 쓰지말기
Promise.reject("Testing static reject").then(
function(success) { // handleSuccess,
// 호출되지 않음
console.log('호출되지 않음')
}, function(error) { // handleError
console.log(error); // "Testing static reject"
});
// type3-2 - catch대신 사용할 수 있는 문법 >> 쓰지말기
// handleError에서 handleSuccess에서 발생하는 throw new Error를 한번에 못받음!!!
Promise.resolve('success').then(
function(success) { // handleSuccess,
throw new Error('== fail ==')
}, function(error) { // handleError
console.log(error); // handleError에서 throw new Error를 한번에 못받음
// 받으려면 handleSuccess,handleError 처리를 계속해야함
error.then(
function(success) { // handleSuccess,
}, function(error) { // handleError
console.log(error);
}
)
});
// DONE catch로 throw new Error() 간단하게 잡을수 있음!!
Promise.resolve('success').then((success) => {
throw new Error('fail')
}).catch((error) => {
console.log(error);
}
);
[NOTE] new Error() 와 throw new Error() 차이
// TODO new Error() 와 throw new Error() 차이
// throw 는 async에서 쓰는건가???
// DONE throw는 catch로 넘기고, return은 then으로 넘긴다.
// 따라서 reject() 내부에 throw를 쓰면 안된다.
function promise4() {
return new Promise((resolve, reject) => {
// SyntaxError: Unexpected token 'throw'
reject(throw new Error("Request is failed"));
});
}
// catch()로 오류를 감지하는 코드
function getData() {
return new Promise(function(resolve, reject) {
resolve('hi');
});
}
// DONE throw는 then 이나 catch 안에서 사용하기?
getData().then(function(result) {
console.log(result); // hi
throw new Error("Error in then()");
}).catch(function(err) {
console.log('then error : ', err); // then error : Error: Error in then()
});