본문 바로가기
FrontEnd

콜백 vs async await

by Chaedie 2022. 7. 12.
728x90

Database와 통신할 때 사용하는 2가지 방법

데이버베이스와 통신할 때 데이터베이스의 동작을 기다리기 위해 두가지 방법이 사용된다. { 1) 콜백함수, 2) 프로미스 } 가 두가지 방법인데, 해당 파트는 javascript 문법에서 중요하고 어렵다고 이야기를 많이 들어온 비동기 처리 부분이다. 한번에 이해가 안될것 같아서 글로 남긴다.

 

아래 콜백 펑션과 async-await의 차이점은 콜백펑션은 콜백이 실행되는 동안 다음 코드들이 실행이 된다는것 (기다려주지 않음), 반면에 await은 해당 동작이 끝날때까지 기다렸다가 끝나면(then) 다음 코드들이 실행된다는 점이다.

 

조금 더 기초적인 개념으로 생각해보면 setTimeout을 실행하면 해당 시간을 기다리는 동안 다음 코드들이 실행되는데 이게 콜백펑션을 사용했을 때의 동작방식이고, 보통 우리가 생각하는 순차적인 코드진행이 (모든 코드가 차례대로 진행) await방식이라고 이해하면 될것 같다.

 

async-await은 어려운 개념이 아니라, 어려운 개념을 원래 알던 방식으로 (순차적 코드 진행 방식) 되돌려주어 쉽게 이해가능하도록 도와준 개념이라고 보면 되겠다.

Call Back Function

export const home = (req, res) => {
  console.log("start home function");
  Video.find({}, (error, videos) => {
    if (error) {
      return res.render('server-error');
    }
   console.log("find videos");
    return res.render('home', { pageTitle: 'Home', videos: [] });
});
  console.log("I'm at the end of the codes");
  console.log(videos);
};
// 출력
// start home funciton 
// I'm at the end of the codes
// find videos

promise function

export const home = async (req, res) => {
  try {
    console.log('start home funciton ');
    const videos = await Video.find({});
    console.log("find videos");
    console.log("I'm at the end of the codes");
      return res.render('home', { pageTitle: 'Home', videos: [] });
  } catch (error) {
    return res.render('server-error');
  }  
};
// 출력
// start home funciton 
// find videos
// I'm at the end of the codes

'FrontEnd' 카테고리의 다른 글

CSR과 SSR  (0) 2022.09.28
[SPA] SPA 프레임워크, 라이브러리 기초  (0) 2022.09.15
[javascript] Type 복습하기  (0) 2022.07.20

댓글