TIL. 비동기

김은서·2022년 7월 27일
0

TIL

목록 보기
20/49

비동기 호출 (Asynchonous call)

callback review

  • 다른 함수(A)의 전달인자(argument)로 넘겨주는 함수(B)
  • parameter를 넘겨받는 함수(A)는 callback 함수(B)를 필요에 따라 즉시 실행(synchronously)할수도 있고, 아니면 나중에(asynchronously) 실행할 수도 있다
function B(){
	console,.log('called at the back!');
}

function A(callback){
	callback(); //callback  === B
}

A(B)

callback in action: 반복 실행하는 함수(iterator)

[1,2,3].map(function(element, index){
	return element * element;
});

callback in action: 이벤트에 따른 함수 (event handler)

document.querySelector('#btn').addEventListener('click', function(e){
	console.log('button clicked');
})

헷갈리지 말기!

function handleClick(){
	console.log('button clicked');
}

//바른 방법

document.querySelector("#btn").onclick = handleClick;

document.querySelector("#btn").onclick = function(){
	handleClick();
}

document.querySelector("#btn").onclick = handlleClick.bind();


//옳지 않은 방법

document.querySelector("#btn").onclick = handlerClick();

// 함수 실행을 연결하는 것이 아님. 함수 자체를 연결하는것

blocking vs non-blocking

전화

: 하던일을 멈추고 받아야함 (blocking) => 요청에 대한 결과가 동시에 일어남 (synchronous)

문자

: 확인 후, 나중에 답장할 수 있음 (non-blocking) => 요청에 대한 결과가 동시에 일어나지 않음(asynchronous)

비동기 함수 전달 패턴 1 : callback 패턴

let request = 'caffelatte';

orderCoffeeAsync(request, function(response){
	//response -> 주문한 커피 결과
    drink(response)
}

비동기 함수 전달 패턴 2 : 이벤트 등록 패턴

let request = 'caffelatte';

orderCoffeeAsync(request).onready = function(response){
	//response -> 주문한 커피 결과
    drink(response)
}

비동기의 주요 사례

  • DOM Element의 이벤트 핸들러

    • 마우스, 키보드 입력(click, keydown 등)
  • 타이머

    • 타이머 API(setTimeout 등)
    • 애니메이션 API(requestAnimationFrame)
  • 서버에 자원 요청 및 응답

    • fetch API
    • AJAX(XHR)

비동기 JavaScript

why Async



sync 효율적이라고 볼 수 있음

callback

순서를 제어하고 싶은 경우에는 어떻게?

const printString = (string) =>{
	setTimeout(
    	() => {
        	console.log(string)
        },
        Math.floor(Math.random() * 100) + 1
    )
}

const printAll =() =>{
	printString('A')
  	printString('B')
    printString('C')
}
printAll() // what do you can expect? 

이 함수는 순서가 랜덤으로 나옴

그래서 callback이 필요함

const printString = (string, callback) =>{
	setTimeout(
    	() => {
        	console.log(string)
            callback()
        },
        Math.floor(Math.random() * 100) + 1
    )
}

const printAll = () => {
	printString('A',()=> {
    	printString('B', () => {
        	printString('C', () => {
            })
        })
    })
} 
printAll() // what do you can expect?

A
B
C

순서대로 나옴

callback error handling Design

const somethingGonnaHappen = callback => {
	waitingUntilSomthingHappen()
    
    if(isSomethingGood){
    	callback(null, something)
    }
    
    if(isSomethingBad){
    	callback(something, null)
    }
}

usage

somethingGonnaHappen((err,data) => {
	if(err){
    	console.log('ERR');
        return
    }
    return data;
}) 

callback 함수 문제점:

callback HELL!!
가독성이 매우 떨어짐

callback 함수 단점을 보완하기 위해서 Promise사용한다고 보면 될듯

Promise

How to deal with callback chain (callback HELL)

promise
: 하나의 class라고 생각하면 될듯

new Promise()를 통해서 인스턴스가 만들어지게 되는데
resolve() = Go to Next Action
reject() = Handle Error
를 통해서 다음 액션으로 넘어가거나 에러를 핸들링 할 수 있음

callback -> promise
동작은 동일하지만, 가독성이 좋아짐 + error 처리할때 마지막에 .catch()로 한번에 할 수 있음

//callback 함수

const printString = (string, callback) =>{
	setTimeout(
    	() => {
        	console.log(string)
            callback()
        },
        Math.floor(Math.random() * 100) + 1
    )
}

const printAll = () => {
	printString('A',()=> {
    	printString('B', () => {
        	printString('C', () => {
            })
        })
    })
} 
printAll() // what do you can expect?


// promise 함수


const printString = (string) => {
    return new Promise((resolve,reject) => {
      setTimeout(
          () => {
              console.log(string)
              resolve()
          },
          Math.floor(Math.random() * 100) + 1
      )
      })
}

const printAll = () => {
	printString('A')
    .then(() => {
    	return printString('B')
    })
    .then(() => {
    	return printString('C')
    })
}

promise도 promise HELL이 있음

return 처리를 잘 해주면 promise HELL을 벗어날 수 있음..

async await

await을 통해서 비동기 함수를 마치 동기적인 함수처럼 쓸 수 있음
async 함수라는 것을 꼭 표시해주어야 함!!

타이머 관련 API

setTimeout(callback, millisecond)

일정 시간 후에 함수를 실행

매개변수(parameter): 실행할 콜백 함수, 콜백 함수 실행 전 기다려야 할 시간 (밀리초)
return 값: 임의의 타이머 ID

setTimeout(function () {
  console.log('1초 후 실행');
}, 1000);
// 123

clearTimeout(timerId)

setTimeout 타이머를 종료

매개변수(parameter): 타이머 ID
return 값: 없음

const timer = setTimeout(function () {
  console.log('10초 후 실행');
}, 10000);
clearTimeout(timer);
// setTimeout이 종료됨.

setInterval(callback, millisecond)

일정 시간의 간격을 가지고 함수를 반복적으로 실행

매개변수(parameter): 실행할 콜백 함수, 반복적으로 함수를 실행시키기 위한 시간 간격 (밀리초)
return 값: 임의의 타이머 ID

setInterval(function () {
  console.log('1초마다 실행');
}, 1000);
// 345

clearInterval(timerId)

setInterval 타이머를 종료

매개변수: 타이머 ID
return 값: 없음

const timer = setInterval(function () {
  console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// setInterval이 종료됨.

+추가

0개의 댓글