콜백함수, 화살표함수

콜백함수, 화살표함수

자바스크립트에서 function(함수)는 object(객체)이다

함수 실행시 조건이 맞지 않으면 바로 종료하도록 빠르게 return을 넣어 짜는 것을 추천

// 비추천 function A (score) { if (score > 10) { // 길고 긴 코드 } }; // 추천 function A (score) { if (score <= 10) { return; } // 길고 긴 코드 };

자바스크립트는 synchronus(동기적)

> 호이스팅이 된 이후부터 작성한 순서대로 실행됨

asynchronus(비동기적)

> 코드가 언제 실행될지 알 수 없음

예) setTimeout();

콜백함수 callback function

함수에서 다른 함수를 인자로 전달해서 호출하는 것

function randomQuiz(answer, printYes, printNo) { if (answer === 'yes') { printYes(); } else { printNo(); } } const printYes = function () { console.log('yes'); } const printNo = function () { console.log('No'); }

동기적 콜백 / 비동기적 콜백

// Synchronous callback function printImmediately(print) { print(); } printImmediately(() => console.log('hello')); // Asynchronous callback function printWithDelay(print, timeout) { setTimeout(print, timeout); } printWithDelay(() => console.log('async callback'), 2000);

콜백지옥

함수에서 콜백함수를 호출하고 전달하고 또 그안에서 호출하고 전달하고 하는 것

!문제점

- 가독성이 떨어짐

- 로직을 한눈에 알아보기가 어려움

- 에러가 발생해서 디버깅 해야 할 때도 어려움

- 유지 보수도 어려움

// Callback Hell example class UserStorage { loginUser(id, password, onSuccess, onError) { setTimeout(()=>{ if ( (id === 'user1' && password === 'password1') || (id === 'user2' && password === 'password2') ) { onSuccess(id); } else { onError(new Error('not found')); } }, 2000); } getRoles(user, onSuccess, onError) { setTimeout(()=>{ if (user === 'user3') { onSuccess({name: 'bong', role: 'admin'}); } else { onError(new Error('no access')); } }, 1000); } } const UserStorage = new UserStorage(); const id = prompt('enter your id'); const password = prompt('enter your password'); UserStorage.loginUser( id, password, user => { UserStorage.getRoles ( user, userWithRole => { alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`); }, error => { console.log(error); } ); }, error => { console.log(error); } )

promise

자바스크립트에서 비동기를 간편하게 처리할 수 있도록 도와주는 오브젝트

콜백함수 대신 유용하게 사용할 수 있음

정해진 기능을 수행하고 정상적으로 작동했다면 성공메세지와 결과값 전달

기능을 수행하다가 문제가 발생하면 에러를 전달

async / await

화살표함수 arrow function

화살표함수는 항상 이름이 없는 함수이다

간결하게 쓸 수 있고 함수형 프로그래밍에 좋음

// 같은 코드 // 함수표현식 const simplePrint = function () { console.log('simplePrint'); } // 화살표함수 const simplePrint = () => console.log('simplePrint');

화살표 함수에서 {}을 사용하면 꼭 return을 사용해서 값을 생략해줘야함

from http://2021bong.tistory.com/121 by ccl(A) rewrite - 2021-12-10 23:27:15