promise의 상태는 3가지 이다.
pending : 무언가를 기다리는 상태
resolved : 성공
reject : 실패
promise는 resolved나 reject일때 특정한 코드를 실행시켜줌
그러려면 함수 안에 콜백을 넣는게 아닌 promise 객체 자체에 콜백을 넣어야함 , 이후 함수가 promise 객체를 반환하는 걸 기다리면 됨.
const fakeRequestPromise = (url) => {
return new Promise((resolve, reject) => {
const delay = Math.floor(Math.random() * (4500)) + 500;
setTimeout(() => {
if (delay > 4000) {
reject('Connection Timeout :(')
} else {
resolve(`Here is your fake data from ${url}`)
}
}, delay)
})
}
이것은 promise 버전의 request 함수이다.
const request = fakeRequestPromise('yelp.com/api/coffee');
request.then(() => {
console.log("IT WORK!")
}).
catch(() => {
console.log("Error!")
})
실행시 IT WORK! 가 출력되는데, 이는 promise가 resolve 되었기 때문이다. (than)
만약 delay값이 > 4000이면 reject 되었기 때문에, Error가 출력된다. (catch)
fakeRequestPromise('yelp.com/api/coffee/page1')
.then(() => {
console.log("IT WORK!")
fakeRequestPromise('yelp.com/api/coffee/page2')
.then(() => {
console.log("IT WORK!2")
fakeRequestPromise('yelp.com/api/coffee/page3')
.then(() => {
console.log("IT WORK!3")
})
.catch(() => {
console.log("Error!3")
})
})
.catch(() => {
console.log("Error!2")
})
}).catch(() => {
console.log("Error!")
})
중첩도 가능하다.
Promise는 return을 사용하면 위처럼 nesting으로 하지 않고도 연쇄가 가능하다.
fakeRequestPromise('yelp.com/api/coffee/page1')
.then((data) => {
console.log("IT WORKED!!!1")
console.log(data)
return fakeRequestPromise('yelp.com/api/coffee/page2')
})
.then((data) => {
console.log("IT WORKED!!!2")
console.log(data)
return fakeRequestPromise('yelp.com/api/coffee/page3')
})
.then((data) => {
console.log("IT WORKED!!!3")
console.log(data)
return fakeRequestPromise('yelp.com/api/coffee/page4')
})
.catch((err) => {
console.log("error")
console.log(err)
})
1번 페이지가 작동 then 2번 then 3번 then 4번....
만약 에러가 발생하면 .catch로 넘어가서 console.log("error") 이 실행된다.또한 then의 콜백에 data를 넣어 맨위 const fakeRequestPromise의 resolve에 속하는Here is your fake data from... 가 출력된다.
'The Web Developer 부트캠프 2022' 카테고리의 다른 글
JS 비동기 async 함수, await (0) | 2022.09.25 |
---|---|
JS Promise 만들기 (1) | 2022.09.25 |
JS 콜백(callback) 지옥 (1) | 2022.09.25 |
기술 콜스택, WebApi와 단일스레드, 콜백 (1) | 2022.09.25 |
JS 이벤트 위임 (1) | 2022.09.23 |