오늘은 promise를 사용할 수 있도록 해 콜백 지옥에서 우리를 구원해줄 bluebird라는 패키지에 대해 알아보도록 하겠습니다.
bluebird는 인기가 아주 많은 패키지입니다.
주간 다운로드 건수가 2000만 번이나 됩니다.
npm i bluebird를 통해 다운로드 할 수 있습니다.
bluebird를 사용하는 이유는 promise를 다른 패키지에서 사용하기 위함입니다.
promise는 비동기 처리의 실패, 이행 등의 상태를 담은 객체로 콜백 함수보다 효율적으로 비동기 처리를 도와줍니다.
needle의 비동기 처리를 활용하여 구현하면 다음과 같습니다.
두 가지 url에서 데이터를 받아온다고 했을 때 아래와 같이 콜백 함수를 두 번 호출해야 합니다.
const needle = require('needle')
var options = {}
var URL_1 = 'https://www.naver.com/'
var URL_2 = 'https://www.daum.net/'
needle.get(URL_1,options,(err,res,body)=>{
if (err) throw err;
console.log(res)
needle.get(URL_2,options,(err,res,body)=>{
if (err) throw err;
console.log(res)
})
})
bluebird를 사용하면. then(),. catch()를 사용해 구현할 수 있습니다.
위의 코드와 가장큰 차이점은 err처리를 한 번만 해주었다는 것입니다.
promise객체가 reject()를 하게 되면. then은 무시하고 catch로 넘어갑니다.
때문에 err 처리를 한 번만 해주면 되는 것이지요.
많은 비동기 처리를 한다고 했을 때 err 처리를 계속 추가해야 하기 때문에 콜백 함수는 점점 복잡해집니다.
또한. then과. catch는 프로세스를 파악하는 것이 쉽지만 콜백 함수는 계속 덮어야 하기 때문에 파악하기가 어렵지요.
const needle = require('needle')
const Promise = require('bluebird')
Promise.promisifyAll(needle)
var options={}
var current = Promise.resolve()
var URL_1 = 'https://www.naver.com/'
var URL_2 = 'https://www.daum.net/'
current.then(()=>{
return needle.getAsync(URL_1,options)
}).then((res)=>{
console.log(res)
}).then(()=>{
return needle.getAsync(URL_2.options)
}).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
코드를 좀 더 분석해 보면 resolve()되면 다음으로 넘어가. then이 실행됩니다.
needle.geyAsync를 통해 동기적으로 url을 정보를 받아오고 변화합니다.
그 반환 값은 다음에 있는 then res에 담깁니다.
만약 에러가 발생하면. catch의 코드가 실행됩니다.
'기타 > node js' 카테고리의 다른 글
자바스크립트 비동기 promise, 콜백함수 예제 (0) | 2020.12.09 |
---|---|
Promise map 사용법 (0) | 2020.12.06 |
nodejs mysql 연동하기 (0) | 2020.12.02 |
자바스크립트 프로미스(Javascript Promise) then catch에 대해 알아보자. (0) | 2020.11.29 |
express 라우터(Router) 사용법 분리 방법 (0) | 2020.11.26 |