티스토리 뷰

콜백 함수(call back func)

// 매개 변수가 있는 사용자 정의 콜백 함수 예제

// 숫자 배열을 입력으로 받아 각 요소를 변환하는 함수
function transformArray(arr, callback) {
  const transformedArray = arr.map(callback);
  return transformedArray;
}

// 사용자 정의 콜백 함수
function squareNumber(num) {
  return num * num;
}

function addOne(num) {
  return num + 1;
}

// 숫자 배열
const numbers = [1, 2, 3, 4, 5];

// squareNumber 함수를 사용하여 숫자 배열의 각 요소 제곱
const squaredNumbers = transformArray(numbers, squareNumber);
console.log("Squared numbers:", squaredNumbers);

// addOne 함수를 사용하여 숫자 배열의 각 요소에 1을 더함
const incrementedNumbers = transformArray(numbers, addOne);
console.log("Incremented numbers:", incrementedNumbers);

 

 

비동기 콜백 함수(async call back func)

// 비동기 콜백 함수 예제

// 비동기 콜백 함수
function delayedFunction(callback) {
  console.log("Start of the delayed function");

  // setTimeout 함수를 사용하여 2초 후에 콜백 함수 호출
  setTimeout(function() {
    console.log("Inside the callback function");
    callback();
  }, 2000);

  console.log("End of the delayed function");
}

// 사용자 정의 콜백 함수
function customCallback() {
  console.log("Callback function executed");
}

// delayedFunction 호출
delayedFunction(customCallback);

console.log("After calling delayedFunction");
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함