콜백함수 - 함수의 파라미터로 들어가 호출되는 함수
ex 1)
const callback = () => console.log("콜백함수"); // 혼자서 실행 X
const fn = callback => callback();
fn(callback); // fn 함수에 파라미터로 callbackFn이 들어가고 함수를 실행 결과, "콜백함수"
ex2)
function fn(callback) {
callback();
}
fn(() => console.log("콜백함수"));
ex3)
words = ['spray','limit','elite','exuberant','destruction','present'];
function myFilter(words, callback) {
var result = [];
for(var word of words) {
if(callback(word)) {
result.push(word);
}
}
return result;
}
newWords = myFilter(words, element => element.length > 6);
console.log(newWords); // 결과, ["exuberant","destruction","present"]
ex4)
const fn1 = callback => {
setTimeout(() => {
console.log("1번 callback");
callback();
}, 1000);
};
const fn2 = callback => {
setTimeout(() => {
console.log("2번 callback");
callback();
}, 1000);
};
const fn3 = callback => {
setTimeout(() => {
console.log("3번 callback");
callback();
}, 1000);
};
console.log("start");
fn1(()=>{
fn2(()=>{
fn3(()=>{
console.log("end")
});
});
});
'Dev > JAVASCRIPT' 카테고리의 다른 글
Javascript JS 제네레이터 (generator) (0) | 2024.02.01 |
---|---|
Javascript JS async / await (0) | 2024.02.01 |
Javascript JS 클래스(class) (1) | 2024.01.31 |
Javascript JS 상속, 프로토타입(prototype) (0) | 2024.01.31 |
Javascript JS call / apply / bind (0) | 2024.01.30 |