250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 내일배움캠프
- useEffect
- 파이썬 반복문
- 파이썬 slice
- 코딩테스트
- REACT
- JavaScript
- 내배캠 프로젝트
- 한글 공부 사이트
- 파이썬 enumerate
- 타입스크립트
- React Hooks
- 타입스크립트 props
- 내일배움캠프 프로젝트
- 파이썬 딕셔너리
- tanstack query
- 내일배움캠프 최종 프로젝트
- typeScript
- useState
- 파이썬 replace
- 리액트
- 리액트 프로젝트
- 파이썬 for
- 파이썬 for in
- 자바스크립트
- 리액트 훅
- 리액트 공식문서
- 프로그래머스
- 타입스크립트 리액트
- Next 팀 프로젝트
Archives
- Today
- Total
sohyeon kim
[JS] 프로미스 Promise(1) resolve, reject, 프로미스 체이닝 본문
728x90
resolve : 성공 시 실행 함수
reject : 실패 시 실행 함수
❗️ 이렇게 어떤 일이 완료된 후 실행되는 함수를 callback 함수라 한다.
// 새로운 Promise가 만들어질 때는 , executor(내가 전달한 콜백 함수)가 바로 실행된다
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
// 네트워크를 이용하거나 파일을 읽어오는 활동을 할 땐 시간이 오래 걸리니
// 실행이 완료된 후 넘어가는 동기적이 아니라
// 실행이 완료되지 않아도 다음으로 넘어가게 비동기적 함수를 이용해야 한다.
console.log(`doing someting...`);
setTimeout(() => {
resolve(`aotoyae`);
// reject(new Error(`no network`));
}, 2000);
});
promise
.then((value) => {
console.log(value); // aotoyae
})
.catch((error) => {
console.log(error); // Error: no network
})
.finally(() => {
console.log(`finally`); // 성공하던 실패하던 마지막에 실행
});
// Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
fetchNumber
.then((num) => num * 2) // 2
.then((num) => num * 3) // 6
.then((num) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000);
}); // 5
})
.then((num) => console.log(num));
// Error Handling
const getTree = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`🌲`), 1000);
});
const getLight = (tree) =>
new Promise((resolve, reject) => {
// setTimeout(() => resolve(`${tree} + 💡`), 1000);
setTimeout(() => reject(new Error(`error! ${tree} + 💡`)), 1000);
});
const onPower = (light) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${light} => 🎄`), 1000);
});
getTree()
// .then((tree) => getLight(tree))
// .then((light) => onPower(light))
// .then((chirstmasTree) => console.log(chirstmasTree));
// 콜백함수를 전달할 때 value를 한가지만 받아서 전달한다면 value 생략 가능!
.then(getLight)
.catch((error) => {
return `🎁`;
}) // getLight에서 error 발생 시 다른 값을 return
.then(onPower)
.then(console.log)
.catch(console.log);
// getTree().then(getLight).then(onPower).then(console.log);
// 가독성이 좋지 않으니 아래처럼 주석 표시를 붙이면 정렬된다.
// getTree() //
// .then(getLight)
// .then(onPower)
// .then(console.log);
🔗 https://youtu.be/JB_yU6Oe2eE?si=87dYAEBJRKIuICbA
728x90
반응형
'JavaScript' 카테고리의 다른 글
[JS] async, await(1) Promise.race (0) | 2023.12.15 |
---|---|
[JS] 프로미스 Promise(2) Promise.all, Promise.race, 프로미스 체이닝 (0) | 2023.12.15 |
[JS] class 클래스, overriding 오버라이딩, 메소드 오버라이딩, (0) | 2023.12.15 |
[JS] 상속, 프로토타입 Prototype, 인스턴스 instance (0) | 2023.12.14 |
[JS] this 지정 call, apply, bind (0) | 2023.12.14 |