콜백함수

Steve·2021년 4월 22일
0

1급 객체란?

자바스크립트에선 배열이나 함수도 객체라고 할 수 있다.

  • 1급객체의 의미:
    컴퓨터 프로그래밍에서 일반적으로 다른 객체들에 적용 가능한 연산을 모두 지원하는 객체.
/// 1) 변수에 담을 수 있다.
let bar = function() { // 익명함수
  return 'JS';
}
console.log(bar());
/// 2) 파라미터로 전달 가능
let number = [1, 2, 3];

number.forEach(function(x) { // 익명함수
  console.log(x * 2);
});
/// 3) 리턴값으로 반환 가능
function test() {
  return function() {
    console.log('js');
  }
}

let bar = test();
bar();

콜백함수

정의 :
파라미터로 함수를 전달 받아, 함수의 내부에서 실행하는 함수
즉, 파라미터로 넘겨받은 함수는 일단 받고, 때가 되면 나중에 호출(callback)한다는 것이 콜백함수의 기본 개념

	function hello(count, team, work) {
      count < 3 ? team() : work();
    }
	function team() {
      console.log("a,b,c,d,e");
    }
	function work() {
      console.log('x,y,z');
    }
 
	hello(2, team, work); // team, work가 콜백함수
// hello가 먼저 호출되고 나중에 2,3 번째 함수가 조건에 따라 실행됨.

정리

함수의 파라미터로 함수가 전달되면 그 함수를 콜백함수라고 한다.

콜백함수 사용원칙

  1. 익명 함수 사용
/// 2) 파라미터로 전달 가능
let number = [1, 2, 3];

number.forEach(function(x) { // 익명함수
  console.log(x * 2);
});
  1. 함수의 이름만 전달
function team() {
  console.log("a,b,c,d,e");
}

function work() {
  console.log('x,y,z');
}

setTimeout(team, 2000); // 이름만 넘긴다
setTimeout(work, 4000);
  1. 전역/지역 변수를 콜백 함수의 파라미터로 전달 가능
let apple = 'apple';

function fruits(callback) {
	let banana = 'banana';
  	callback(banana);
}

function eat(banana) {
  console.log(`apple: ${apple} / banana : ${banana}`);
}

fruit(eat);

  • 콜백함수 비동기 처리 예제
console.log('hi');
setTimeout(function() {
	console.log('bye');
} 3000);
console.log('hi again');

// hi
// hi again
// bye (3초 후 출력)

*콜백지옥이란?

함수의 함수의 함수의 ... 무한 반복
비동기 프로그래밍 시 발생하는 문제.
함수의 파라미터로 넘겨지는 콜백함수가 반복되어 코드의 들여쓰기 수준이 매우 깊어지는 현상

function square(x, callback) }{
  setTimeout(callback, 100, x*x);
}

square(2, function(x) {
  square(x, function(x2) {
    square(x2, function(x3) {
      console.log(x3);
    });
  });
});

콜백지옥의 해결책

  1. 콜백 함수를 분리
square(x, callback) {
  setTimeout(callback, 100, x*x);
}

function firstCallback(number) {
  square(number, secondCallback);
}
function secondCallback(number) {
  square(number, thirdCallback);
}
function thirdCallback(number) {
  console.log(number);
}

square(2, firstCallback);

2.es6부터 나온 promise, async/await 사용

let _promise = function(param) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if(param) {
        resolve('해결!');
      }else{
        reject(Error('실패ㅜ');
      }
    }, 1000);
  });
);

sol? -> promise, async,await
https://velog.io/@ksung1889/Promise-async-await

profile
Front-Dev

0개의 댓글