[TSR] 비동기 호출과 요청

EllaDev·2022년 1월 19일
0

today-study-record

목록 보기
2/8
post-thumbnail

해당글은 오늘 공부한 내용을 정리하여 메모하는 형식으로 작성한 것으로 설명이나 이해를 돕는 글이 아님을 명시합니다.


Before start..

용어정리

  • blocking : 하나의 작업이 끝날 때까지, 이어지는 작업을 "막는 것"
  • non-blocking: 하나의 작업이 끝날 때까지, 이어지는 작업을 막지 않고 진행하는 것

비동기적 실행

  • Node.js: non-blocking하고 비동기적(asynchronous)으로 작동하는 런타임으로 개발
  • 웹개발
    • 백그라운드 실행, 로딩 창 등의 작업
    • 인터넷에서 서버로 요청을 보내고, 응답을 기다리는 작업
    • 큰 용량의 파일을 로딩하는 작업


비동기 호출

비동기 호출이란?

callback

  • 정의 : 다른 함수에 전달인자로 넘겨주는 함수
  • 매게변수로 넘겨받은 함수는 Callback함수를 동기적으로 실행 할 수도 있고 비동기적으로 실행 할 수도 있다.

callback 실행 상황

  • 반복실행하는 함수
  • 이벤트에 따른 함수(event handler)
    • 주의사항

동기

blocking

  • 하던일을 멈추고 받아야한다.
  • 요청에 대한 결과가 동시에 일어남
  • ex> 전화

비동기

non-blocking

  • 확인 후, 나중에 답장할 수 있다.
  • 요청에 대한 결과가 동시에 일어나지 않는다.
  • 이벤트(trigger) 실행에 의해서 event handler(callback)가 실행

비동기 함수 전달 패턴

/* callback 패턴 */
 let request= 'coffee'
 orderCofffeeAsync(request, function(res){
 	drink(res)
 })
/* 이벤트 등록 패턴 */
 let request= 'coffee'
 orderCofffeeAsync(request).onready = function(res){
	drink (res) 
 }

동기와 비동기 코드로 구현

비동기 주요 사례

  • Dom Element 이벤트 핸들러
    • 마우스,키보드 입력(click, keydown 등)
    • 페이지 로딩(DOMContentLoaded 등)
  • 타이머
    • 타이머 API(setTimeout등)
    • 애니메이션 API(requestAnimationFrame)
  • 서버에 지원 요청 및 응답
    • fetch API
    • Ajax(XHR)

비동기 Javascript

Why Async?

  • 하나의 일을 요청하고 그 일이 끝날때까지 아무것도 할 수 없는 sync는 서비스는 사용자에게 친화적이지 않다.
  • 내부적으로는 Event Loop를 이용해서 처리된다.

Callback

  • Async에서 순서를 제어하고 싶은 경우
 const printString = (string)=>{
  setTimeout(function () {
    console.log("callback ", string);
  }, Math.floor(Math.random() * 100) + 1);
};

const printAll = () => {
  printString("A");
  printString("B");
  printString("C");
};

printAll();

// callback 사용
const printString = (string, callback) =>{
  setTimeout(function () {
    console.log("callback ", string);
    callback();
  }, Math.floor(Math.random() * 100) + 1);
};

const printAll = () => {
  printString("A", ()=> {
    printString("B", ()=>{
      printString("C", ()=> {
      });
    });
  });
};

printAll();

error handling

const somethingHappen = (callback) => {
  waitingUtilSomethingHappens()
  if(isGood){
    callback(null,something)
  }
  if(isBad){
    callback(something, null)
  }
}

// 사용 예제 
somethingHappen((err, data)=> {
  if(err){
    console.log('Err')
    return;
  }
  return data;
})

Promise

  • Callback의 단점(callback hell)을 보안해주는 기술
  • Callback보다 가독성이 좋다.
  • 기능은 callback과 같다.
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")
  })
};

printAll();

Primise Hell

  • return 처리를 잘 하면(promise chaining) 어느 정도 처리 가능하지만 그렇지 않으면 얼마든지 hell을 경험 할 수 있다.
function gotoCode1(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('1. first')}, 100)
  })
}

function gotoCode2(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('2. Second')}, 400)
  })
}

function gotoCode3(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('3. Third')}, 300)
  })
}

function gotoCode4(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('4. Forth')}, 200)
  })
}

gotoCode1()
.then(data=>{
  console.log(data);
  
  gotoCode2()
  .then(data=> {
  	console.log(data)
     
    gotoCode3()
     .then(data=> {
        console.log(data)
        
        gotoCode4()
        .then(data=> {
          console.log(data)
        })
     })
  })
})

async await

  • Promise인데 좀더 편하게 쓸수 있게 해준다.
  • 코드가 마치 동기처럼 보이도록 표현한다.
  • async함수안에서만 await를 쓸 수 있다.
function gotoCode1(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('1. first')}, 200)
  })
}

function gotoCode2(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('2. Second')}, 500)
  })
}

function gotoCode3(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('3. Third')}, 100)
  })
}

function gotoCode4(){
  return new Promise((resolve, reject) => {
  	setTimeOut(()=>{ resolve('4. Forth')}, 300)
  })
}

const result = async () => {
	const one = await gotoCode1()
    console.log(one);
  
	const two = await gotoCode2()
    console.log(two);
  
	const three = await gotoCode3()
    console.log(three);
  
	const four = await gotoCode4()
    console.log(four);
}

result();

[비동기 처리 예시](https://codesandbox.io/s/async-network-fbioo?file=/src/practice/basicChaining.js)

Timer API

setTimeout(callback, millisecond)

일정 시간 후에 함수를 실행

  • arguments: 실행할 callback 함수, callback 함수 실행 전 기다려야 할 시간 (밀리초)
  • return value: 임의의 타이머 ID
setTimeout(function () {
  console.log('1초 후 실행');
}, 1000);
// 123

setInterval(callback, millisecond)

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

  • arguments: 실행할 callback 함수, 반복적으로 함수를 실행시키기 위한 시간 간격 (밀리초)
  • return value: 임의의 타이머 ID
setInterval(function () {
  console.log('1초마다 실행');
}, 1000);
// 345

clearInterval(timerId)

반복 실행중인 타이머를 종료

  • arguments: 타이머 ID
  • return value: 없음
  • setTimeout에 대응하는 clearTimeout도 있음
const timer = setInterval(function () {
  console.log('1초마다 실행');
}, 1000);
clearInterval(timer);
// 더 이상 반복 실행되지 않음
// 123

Nodejs 모듈

Nodejs 모듈이란?

Node.js

  • Node.js는 많은 API가 비동기로 되어있다.
  • Node.js"비동기 이벤트 기반 자바스크립트 런타임" 이라고 정의되어 있다.
  • 로컬 환경에서 자바스크립트를 실행할 수 있는 자바스크립트 런타임이다.

모듈이란?
건축으로부터 비롯된 모듈이라는 단어는, 어떤 기능을 조립할 수 있는 형태로 만든 부분이다. fs(File System) 모듈은, PC의 파일을 읽거나 저장하는 등의 일을 할 수 있게 도와준다.

Node.js 내장 모듈을 사용하는 방법

  • 모든 모듈은 '모듈을 사용하기 위해 불러오는 과정'이 필요하다.
  • 브라우저에서 다른 파일을 불러올 때에는 다음과 같이 <script> 태그를 이용했지만 Node.js 에서는 자바스크립트 코드 가장 상단에 require 구문을 이용하여 다른 파일을 불러옵니다.
const fs = require('fs'); // 파일 시스템 모듈을 불러옵니다
const dns = require('dns'); // DNS 모듈을 불러옵니다

3rd-party 모듈을 사용하는 방법

  • 3rd-party module : 해당 프로그래밍 언어에서 공식적으로 제공하는 빌트인 모듈(built-in module)이 아닌 모든 외부 모듈을 말한다.
  • npm으로 설치하여 사용

Node.js 공식문서 가이드

fs.readFile 공식문서

fs.readFile(path[, options], callback)

  • fs.readFile 은 비동기적으로 파일 내용 전체를 읽는다.
  • 메소드를 실행할 때에는 인자 세 개를 넘길 수 있다.

path \<string> | \<Buffer> | \<URL> | \<integer>

  • path : 파일 이름를 인자로 넘길 수 있다.
  • 4가지 타입 : string, Buffer, URL, integer
fs.readFile('/etc/passwd', ..., ...)

options \<Object> | \<string>

  • 대괄호는 생략 가능한 인자로 option은 생략 가능하다.
let options = {
  encoding: 'utf8', // UTF-8이라는 인코딩 방식으로 엽니다
  flag: 'r' // 읽기 위해 엽니다
}

// /etc/passed 파일을 옵션을 사용하여 읽습니다.
fs.readFile('/etc/passwd', options, ...) 

callback \<Function>

  • 파일을 읽고 난 후에 비동기적으로 실행되는 함수
  • 파라미터
    • error : error발생 안하면 null값
    • data : 문자열이나 Buffer 라는 객체가 전달
fs.readFile('test.txt', 'utf8', (err, data) => {
  if (err) {
    throw err; // 에러를 던집니다.
  }
  console.log(data);
});


비동기 요청

Fetch API

  • Fetch API는 URL로 네트워크 요청이 가능하게 한다.
  • 특정 URL로부터 비동기적으로 정보를 받아오는 역할을 한다.
fetch(url)
  .then((response) => response.json()) // 자체적으로 json() 메소드가 있어, 응답을 JSON 형태로 변환시켜서 다음 Promise로 전달합니다
  .then((json) => console.log(json)) // 콘솔에 json을 출력합니다
  .catch((error) => console.log(error)); // 에러가 발생한 경우, 에러를 띄웁니다

추가적으로 스터디 필요한 것

profile
Frontend Developer

0개의 댓글