콜백함수,promise보충하기-생활코딩+드림코딩 강의정리😁

시유야·2023년 3월 20일
0
post-thumbnail

01 callback

댓글중...
call at the back - 함수를 호출한 다음 그 뒤에서 호출되어 할 일을 지시하는 함수라고 생각해.
함수이기는 함수인데 다른 함수에 의해 호출이 되는 함수

함수A가 표현되어 있어. A함수가 B함수의 parameter로 전달이 되서 그 함수 내부에서 호출이 되었다면 이 맥락에서 A함수는 callback function이 된다.

일급객체

  • 함수가 다른 함수의 리턴값으로
  • 함수가 다른 함수의 입력값으로(parameter)

array.filter()

const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 
//6개의 요소를 가진 words라는 배열이 있다

const result = words.filter(word => word.length >6);

console.log(result);
//출력>> array['exuberant', 'destruction', 'present']

filter라는 함수에 (word => word.length >6)가 함수로 전달이 되어있는데, 이 부분을 callback 함수라고 한다.

arr.filter함수 뜯어보기

arr.filter(callback(element[, index[, array]])[, thisArg])

  • filter함수는 함수(여기서 callback())를 입력받는 함수이다.

  • 입력받는 함수는 3개의 변수를 입력할 수 있는데, 그 중 element는 필수이고, index, array 는 옵션이다.

  • callback 함수는 각 요소를 시험했을 때,
    true를 반환하면 그 요소를 사용하고,
    false를 반환하면 그 요소는 버린다.

  • element : 판단해야하는 각각의 원소

여러방식으로 고쳐보기

const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 

function callback(element) {
  console.log(element);
}
words.filter(callback);
//콘솔 창 출력 >> spray / limit/ ... 전체 요소 찍힘

const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 

function callback(element) {
  if(element.length >6) {
    return true;
  } else {
    return false;
  }
}
newWords = words.filter(callback);
console.log(newWords);  // 콘솔 출력 >> ['exuberant', 'destruction', 'present']

더 줄이기


const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 

function callback(element) {
    return element.lentgh > 6;
  }
}
newWords = words.filter(callback);
console.log(newWords);

콜백함수는 거의 1회성이 많기때문에 굳이 이름을 붙여줄 필요가 없고, 콜백함수를 소비하는 함수가 멀리 떨어져있지.. 더 고치기


const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 
const newWords = words.filter(function(element) {
  return element.length > 6;
});
console.log(newWords);

function 생략하고 arrow function 사용하기


const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 

const newWords = words.filter((element)=> {
  return element.length > 6;
});
console.log(newWords);

코드가 한 줄이면 중괄호와 리턴조차도 필요없지


const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 

newWords = words.filter(element=> element.length > 6);
console.log(newWords);

콜백함수를 소비하는 함수 생성해보기

words.filter와 똑같이 동작하는 myfilter함수를 만들어보기

const words = ['spray', 'limit', 'elite','exuberant', 'destruction', 'present']; 
function myfilter(origineElem, callback) {
  var result = [];
  for (let i=0; i<originElem.length;i++) {
    var current = originElem[i];
    if(callvack(current)) {
      result.push(current);
    }
  }
  return result;
}
const newWords = myfilter(words, element => elem.length > 6);
console.log(newWords);

동기콜백, 비동기콜백 (출처 : 드림코딩)

//동기처리
function printImmediately(print) {
  print();
}
printImmediately(() => console.log('hello'));

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

1.콜백 함수 & 동기 처리
printImmediately함수는 print되는 함수를 매개변수로 받아서 함수 실행 시 호출 할수 있도록 선언했다. 이 함수를 호출할 때 함수를 전달받아서 호출이 될 수 있도록 콜백함수를 인자로 써서 넘겨준 것이다. print자리에 hello 가 찍힐 수 있는 화살표 함수를 넣어주었기 때문에 print();가 가능한 것
2. 콜백 함수 & 비동기 처리
print와 timeout을 web api인 setTimeout() 에 넘겨줄 수 있는, setTimeout을 래핑하고 있는 printWithDelay함수를 생성한다. 호출할 때 원하는 기능을 동작할 수 있도록 콜백함수로 전달(여기서는 화살표 함수로 콘솔로그사용)을 해야하고, 지연하고 싶은 시간을 콤마 뒤에 써준다.

setTimeout()사용법

  • 원하는 코드를 바로 실행하지 않고 일정 시간동안 기다렸다가 실행하고 싶을 때 사용하는 함수
  • setTimeout(실행할 코드를 담고 있는 함수, 지연 시간(ms))

02 Promise

synchronous | asynchronous (동기 | 비동기)

동기 - 코드 위에서부터 아래로 순차적 실행

먼저 실행된 코드가 종료되어야 다음 코드가 실행될 수 있다.

비동기 - 일종의 멀티태스킹(병렬실행)

언제 사용할까?
1. 언제 끝날지 예측이 어려운상황 (예: 서버와 웹브라우저의 통신)
2. 주된(중요한) 처리가 아닌 경우
(참고 ajax - 브라우저와 웹서버가 자바스크립트 코드를 가지고 통신하는 것 (페이지 새로고침 없이)

드림코딩 promise 추가정리

  1. Promise란 ?
    비동기 수행을 위한 자바스크립트 내장 객체
  2. 상태 : pending -> fulfilled or rejected
  3. Producer vs Consumer
  • producer
    😎 Promise객체가 생성이되면 자동적으로 executor라는 콜백 함수가 바로 실행이 된다!!!
    😎 executor -> resolve() or reject()라는 콜백함수를 사용할 수 있다.
    resolve() : 성공 시 데이터를 반환할 수 있는 콜백함수
    reject(): 처리 중 문제가 생기면 실행되는 콜백함수

  • consumers
    😎 .then, .catch, .finally라는 함수로 값을 받아올 수 있다.

//Promise Producer
const promise = new Promise((resolve, reject) => {
  //doing some heavy work() 시간이 걸리는...
  
  setTimeout(()=> {
    resolve('성공');
    //reject(new Error('no network');
  }, 2000);
});

//Promise Consumers : then,catch, finally
//resolve에서 넘겨준 데이터를 value 로 값을 받아와서 원하는 기능을 수행하는 콜백함수를 전달해준다!
promise
  .then(value=> {
  console.log(value);   // '성공'
  }
  .catch(error => {
    console.log(error);
  }
  .finally(()=> {
    console.log('finally');
  }
});

  • Promise 객체 내에서 생성된 reject()내부에 Error라는 클래스는 자바스크립트에 내장된 객체. 에러의 원인 메세지로 작성해서 내보내야 한다.

fetch API사용하기

fetch()함수의 형태
fetch(resource, [, init])

  • resource : url을 준다.

  • return value : A Promise that resolves to a Response Object.
    성공적으로 실행이 되면 Resoponse라는 객체 타입을 전달한다.

  • fetch의 리턴값은 promise!!!
    promise로 리턴이 되면 두가지 타입의 메서드를 사용할 수 있다.

  • 1..then(callback() {}) : fetch가 성공하면 then으로 전달된 callback함수를 호출한다.

  • 2..catch(callback() {}) : fetch가 실패 시 catch로 전달된 callback함수 호출

fetch('https://www.naver.com')
	.then(function(response) {  //네이버 서버에서 요청받아오기 성공하면
  		console.log('response', response);
	})
	.catch(function(reason) {  //실패하면
  		console.log('reason', reason);
	});

promise chaining

fetch('https://jsonplaceholder.typicode.com/posts')
	.then(function(response) { 
  		return resoponse.json();
	})
	.catch(function(reason) {  
  		console.log('reason', reason);
	})
	.then(function(data) { 
  		console.log('data', data);
	});

json타입의 데이터를 보내는 서버에 요청을 했을 때 promise 객체로 데이터를 받아오는데 성공했다면 then으로 받아서 콜백함수를 실행시킨다.
이 때 return값이 response.json()인데 이것도 promise객체로 받는다.
json타입의 데이터를 자바스크립트 코드로 변환해서 받아오는 것에 성공을 하면 마지막 then 으로 받아서 콘솔에 찍어주는 코드이다.
바깥쪽에서 then과 then을 연결하는 것을 promise chaining이라고 부른다.

03 async & await

promise를 사용하고 있는 비동기 함수를 동기 함수처럼 사용할 수 있게 해주는 도구인 async와 await를 알아본다.

드림코딩

인용 : 생활코딩 , 드림코딩

profile
i'm happy enough.

0개의 댓글