Front End/JavaScript
[JS] Avoid callback hell, Promise
옐 FE
2021. 6. 20. 13:13
udemy, The Complete JavaScript Course 2021: From Zero to Expert!
/ Teacher: Jonas Schmedtmann
Promise chain을 사용하는 목적은 Callback HELL에서 벗어나기 위함이다.
Promise : An object that is used as a placeholder for the future result of an asynchronous operation.
'AJAX call과 같은 미래에 받을 값을 담아놓는 상자' 정도로 이해하면 될 거 같다.
setTimeout(() => {
console.log('1 second passed');
setTimeout(() => {
console.log('2 seconds passed');
setTimeout(() => {
console.log('3 seconds passed');
}, 1000);
}, 1000);
}, 1000);
Callback Function 여러 개로 만들어진 읽기 힘든 코드를,
const wait = function(seconds) {
return new Promise(resolve => setTimeout(resolve, 1000 * seconds))
};
wait(1)
.then(() => {
console.log('1 second passed');
return wait(1)
})
.then(() => {
console.log('2 second passed');
return wait(1)
})
.then(() => console.log('3 second passed'));
Promise로 코드를 짤 수 있다.