new Promise((resolve, reject) => {
resolve();
})
Promise 코드의 기본 원리
const fakeRequest = (url) => {
return new Promise((resolve, reject) => {
const rand = Math.random();
setTimeout(() => {
if (rand < 0.7) {
resolve("Data here!");
}
reject("error");
}, 1000)
})
}
이렇게 Promise 코드를 응용해 rand의 값에 따라 resolve 값을 전달할지 reject값을 전달할지 코드를 짤 수 있다.
fakeRequest('/dogs/1')
.then((data) => {
console.log("DONE WITH REQUEST!")
console.log('data is:', data)
return fakeRequest('/dogs/2')
})
.then((data) => {
console.log("DONE WITH REQUEST!")
console.log('data is:', data)
return fakeRequest('/dogs/3')
})
.then((data) => {
console.log("DONE WITH REQUEST!")
console.log('data is:', data)
return fakeRequest('/dogs/4')
})
.then((data) => {
console.log("DONE WITH REQUEST!")
console.log('data is:', data)
return fakeRequest('/dogs/5')
})
.catch((err) => {
console.log("ERROR!", err)
})
해당 코드는 이렇게 응용이 가능하다 .
const delayedColorChange = (color, delay) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
document.body.style.backgroundColor = color;
resolve();
}, delay)
})
}
이렇게 setTImeout을 설정해 body의 색을 바꾼 후 resolve를 사용해 .then을 이용하면 다음으로 계속 넘어가게 가능
delayedColorChange('red', 1000)
.then(() => delayedColorChange('orange', 1000))
.then(() => delayedColorChange('blue', 1000))
.then(() => delayedColorChange('olive', 1000))
.then(() => delayedColorChange('yellow', 1000))
.then(() => delayedColorChange('peel', 1000))
.then(() => delayedColorChange('pink', 1000))
'The Web Developer 부트캠프 2022' 카테고리의 다른 글
JS Try, catch 를 이용한 async 문제 해결 (0) | 2022.09.25 |
---|---|
JS 비동기 async 함수, await (0) | 2022.09.25 |
JS Promise (2) | 2022.09.25 |
JS 콜백(callback) 지옥 (1) | 2022.09.25 |
기술 콜스택, WebApi와 단일스레드, 콜백 (1) | 2022.09.25 |