Node.js) 비동기 프로그래밍 (Asynchronous Programming) 공부해보기

2023. 3. 4. 01:20개발/Node.js

728x90

Chapter

2023.03.03 - [개발/MongoDB] - MongoDB) 계정 만들고 db 생성하고 CRUD 해보기

2023.03.03 - [개발/Node.js] - Node.js) 설치부터 REST API 만들어보기

2023.03.04 - [개발/Node.js] - Node.js) 비동기 프로그래밍 (Asynchronous Programming) 공부해보기

2023.03.04 - [개발/Node.js] - Node.js) MongoDB 접속 후 DB 다루기

참고

 

해당 내용은 강의를 기반으로 작성하였습니다. 
강의를 들으면 더욱 상세한 내용을 얻으실 수 있으니, 강의를 듣기를 권장합니다.
https://www.inflearn.com/course/%EB%AA%BD%EA%B3%A0%EB%94%94%EB%B9%84-%EA%B8%B0%EC%B4%88-%EC%8B%A4%EB%AC%B4/dashboard

Blocking vs Non-blocking

한 사람이 하나의 일이 끝날 때 까지 계속 기다리는 것이 Blocking이고, 

Non Blocking은 하나를 처리하고 또 다른 것을 처리하는 것을 Non-Blocking이라 한다.

 


Non-Blocking이라는 것을 하려면 필요한 것이 보통은 Queue가 필요하다.

 

주방장 : 데이터 베이스

웨이터 : node.js

Event Loop가 Thread Pool이 끝나는 것을 확인한다.

 

 

callback

callback.js

const addSum = (a, b, callback) => {
    setTimeout(() => {
        if (typeof a !== 'number' || typeof b !== 'number') return callback('a,b must be numbers');
        callback(undefined, a + b)
    }, 3000);
}

addSum(10, 20, (error, sum) => {
    if (error) return console.log({ error });
    console.log({ sum })
}
)

let callback = (error, sum) => {
    if (error) return console.log({ error });
    console.log({ sum })
}

addSum(10, 20, callback)
addSum(10, 'a', callback)

 

 

promise

Promise의 세가지 상태

  • pending(대기): fulfilled(이행)도 rejected(거절)도 안된 초기 상태
  • fulfilled(이행): 비동기 연산이 성공적으로 완료된 상태, 결과값을 반환한다.
  • rejected(실패): 비동기 연산에 실패한 상태, 에러를 반환한다.

 

promise.js

const addSum = (a, b) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (typeof a !== 'number' || typeof b !== 'number') {
                reject('a,b must be numbers');
            }
            resolve(a + b)
        }, 3000);
    })
}

addSum(10, 20)
    .then((sum) => console.log({ sum }))
    .catch((error) => console.log({ error }))

addSum(10, "a")
    .then((sum) => console.log({ sum }))
    .catch((error) => console.log({ error }))

 

Chained Promises

 

nested 된 구조를 짜게 되면, 계속 가로 안에 가로로 들어가지만 점점 더 복잡해짐

callback.js 버전

addSum(10, 20, (error1, sum1) => {
    if (error1) return console.log({ error1 });
    console.log({ sum1 })
    addSum(sum1, 15, (error2, sum2) => {
        if (error2) return console.log({ error2 });
        console.log({ sum2 })
    })
})

promise.js 버전

훨씬 간결해짐!

특히 에러가 나도 하나의 catch로 처리할 수 있음!

주요 비즈니스 로직은 promise를 많이 사용한다고 함.

 

 

then()과 catch() 메소드는 Promise 객체를 반환하므로 chaining 형태로 사용될 수 있다.

addSum(10, 20)
    .then(sum1 => addSum(sum1, 15))
    .then(sum2 => console.log({ sum2 }))
    .catch((error) => console.log({ error }))
    
addSum(10, 20)
    .then(sum1 => {
        return addSum(sum1, 15)
    })
    .then(sum2 => console.log({ sum2 }))
    .catch((error) => console.log({ error }))
    

addSum(10, 20)
    .then(sum1 => {
        console.log({ sum1 })
        return addSum(sum1, 'sd')
    })
    .then(sum2 => console.log({ sum2 }))
    .catch((error) => console.log({ error }))
    
addSum(10, 20)
    .then(sum => addSum(sum, 1))
    .then(sum => addSum(sum, 1))
    .then(sum => addSum(sum, 1))
    .then(sum => addSum(sum, 1))
    .then(sum => addSum(sum, 1))
    .then(sum => console.log({ sum }))
    .catch((error) => console.log({ error }))

 

더 간결하게 하는 문법이 있다고 함.

중간 중간 값을 확인하려면 then 쪽이 복잡해짐.

하지만 async를 사용하면 더 간결하게 가능함.

try catch로 감싸서 에러 로그 처리

addSum(10, 10)
    .then(sum1 => {
        sum1_ = sum1
        return addSum(sum1, 10)
    })
    .then(sum2 => {
        sum2_ = sum2
        console.log({ sum2 })
    })

const totalSum = async () => {
    try {
        let sum = await addSum(10, 10)
        let sum2 = await addSum(sum, 10)

        console.log({ sum2 })

    } catch (err) {
        if (err) console.log({ err })

    }
}

 

빨간색 영역 : non blocking

파란색 영역 : blocking

 

일반 동기 프로그래밍

비동기프로그래밍

노드가 겹치는 영역은 cpu를 놀지 않고 일을 시킨다.

 

 

상황에 따라 동기 비동기에 따라서 아래처럼 구성

유저는 일단 찾고, 유저가 있다면 한번에 insert 및 update를 진행시킴

이런식으로 시간을 절약할 수 있는 것이 장점이다.

Blocking

- 빨간색 부분이 노는 부분인데, Blocking이 되면 일을 못하게 된다.(많은 처리가 안됨)

- 다른 쪽에서 처리하게 한다. (child process) 같은 것을 만든다는지...

참조

https://interconnection.tistory.com/141

 

Blocking or Non-Blocking, Synchronous and Asynchronous

Overview When we develop application, we always think concepts called "Blocking, Non-blocking, Synchronous, Asynchronous". We usually think that "Blocking, non-blocking, Synchronous, Asynchronous" are the same. But, This perspective is wrong. It is unrelat

interconnection.tistory.com

 

github

https://github.com/sungreong/mongodb_and_nodejs_study.git

 

728x90

'개발 > Node.js' 카테고리의 다른 글

Node.js) MongoDB 접속 후 DB 다루기  (2) 2023.03.04
Node.js) 설치부터 REST API 만들어보기  (0) 2023.03.03