Callback Function
Javascript 엔진은 single thread로 동작
Ajax call이라던가, setTimeout 등 시간이 오래걸리는 일이 수행되어야 한다면, 이 일이 끝날 때까지 작업이 멈추게 된다.
이러한 경우는 함수를 미리 등록만 해두고, 어떤 일이 완료된 후 해당 함수가 실행하도록 하는게 하는 것을 Callback function 이라고 한다.
// 예시
const a1 = (func) => {
setTimeout(() => {
console.log('1');
func();
}, 2000);
}
const a2 = (func) => {
setTimeout(() => {
console.log('2');
func();
}, 3000);
}
a1(() => {
a2(() => {
console.log('end');
});
});
1 // 2초 후
2 // 다시 3초 후
end
Callback function 중첩이 되면 복잡해지고 '콜백 지옥' 이라는 것이 생성된다.
이를 보완하기 위해 promise나 async, await를 사용한다.
Promise
promise 함수에 resolve와 reject라는 2개의 Callback Function을 동록한다.
성공시 resolve가 불리고, 실패시 reject가 불린다.
const a = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success');
// reject(new Error('fail'));
}, 1000)
});
a.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
}).finally(() => {
console.log('end');
});
a는 promise 객체를 return 받는데 객체에 state와 result가 존재한다.
state는 pending이었다가 1초 후 성공시 fulfilled로 되고 실패 시 reject가 된다.
result는 undefined였다가 전달받은 'success' 또는 error 객체가 된다.
모든 수행 완료시 finally를 수행한다.
const a1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success a1');
}, 2000);
})
}
const a2 = (data) => {
console.log(data);
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success a2');
}, 3000);
})
}
a1()
.then((result) => a2(result))
.then((result) => console.log(result))
.finally(() => {
console.log('end');
});
Promise가 연결되는 것을 promise chaining이라고 한다.
a1에서 받아온 data를 a2에서 사용하고 있다. a1이 2초, a2가 3초, 총 5초가 소모된다.
앞에서 받아온 값을 사용해도 되지 않을 경우(독립적 상황)에서는 비효율적인 동작이 된다.
병렬적 동작에는 Promise.all이 사용된다.
Promise.all([a1(), a2()]).then((result) => {
console.log(result);
});
// 아래 결과값은 a2에있는 console.log(data)부분을 무시하고 작성하였다. 실제로는 undefined가 출력된다.
['success a1', 'success a2']
result에는 차례대로 결과가 출력된다.
순서를 보장하며, 하나라도 실패시 실패로 처리한다.
이 때 Promise.all이 아닌 Promise.race를 사용하는 경우 하나라도 완료되었을 때 종료된다.
'Programming Language > Javascript' 카테고리의 다른 글
Execution Context(실행 컨텍스트) (0) | 2022.07.31 |
---|---|
Javascript에서의 this (0) | 2022.07.19 |
http protocol (0) | 2016.01.22 |
JSON (0) | 2016.01.21 |
jquery (0) | 2016.01.20 |