728x90
반응형
/**
* Callback
*/
function waitAndRun() {
setTimeout(() => {
console.log('끝');
}, 2000);
}
waitAndRun(); // 2초 뒤 끝
function waitAndRun2() {
setTimeout(
() => {
console.log('1번 콜백 끝');
setTimeout(() => {
console.log('2번 콜백 끝');
setTimeout(() => {
console.log('3번 콜백 끝');
}, 2000);
}, 2000);
}, 2000);
}
waitAndRun2();
/**
* 2초간격으로 순차적으로
* 1번 콜백 끝
* 2번 콜백 끝
* 3번 콜백 끝
*/
/**
* Promise
*/
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('완료');
}, 2000);
});
timeoutPromise.then((res) => {
console.log('---then---');
console.log(res);
});
const getPromise = (seconds) => new Promise((resolve, reject) => {
setTimeout(() => {
// if(xxx){
// resolve('성공')
// }else{
// reject('에러');
// }
resolve('에러');
}, seconds * 1000);
});
getPromise(3)
.then((res) => {
console.log('--- first then ---');
console.log(res);
})
.catch((res)=>{
console.log('--- first catch ---');
console.log(res);
})
.finally(()=>{
console.log('--- finally ---');
});
Promise.all([
getPromise(1),
getPromise(4),
getPromise(1),
]).then((res)=>{
console.log(res);
});
/**
* --- first then ---
* 에러
* --- finally
*/
728x90
반응형
'코드팩토리 JS' 카테고리의 다른 글
| 29. async await (0) | 2025.12.28 |
|---|---|
| 27. async theory (0) | 2025.12.27 |
| 26. closure (0) | 2025.12.27 |
| 25. execution context (0) | 2025.12.27 |
| 24. this (0) | 2025.12.27 |