728x90
오늘은 promise.map에 대해서 알아보도록 하겠습니다.
promise.map은 .push와 .all을 하나로 대체하는 함수입니다.
promise.map은 mapper함수에 의해 반환된 promise가 기다리고 있고, 모든 값에 대해 fulfill되었을 때 비로소 .then뒤의 코드를 실행할 수 있다.
만약 한가지라도 reject되면 .catch가 실행됩니다.
예시를 통해 알아보도록 하겠습니다.
예시는 여러개의 url에 접속해 처리한 후 한 번에 데이터를 받아오는 코드입니다.
const needle = require('needle')
const Promise = require('bluebird')
Promise.promisifyAll(needle)
var urls = ['https://www.naver.com/',
'https://www.daum.net/',
'https://github.com/']
var options = {}
Promise.map(urls, (url) => {
return needle.getAsync(url, options);
}).then((res) => {
console.log(Object.keys(res))
console.log(res[0].socket.servername);
console.log(res[1].socket.servername)
console.log(res[2].socket.servername)
}).catch((err)=>{
console.log(err)
})
const needle = require('needle')
const Promise = require('bluebird')
Promise.promisifyAll(needle)
var urls = ['https://www.naver.com/',
'https://www.daum.net/',
'https://githsub.com/']
var options = {}
Promise.map(urls, (url) => {
return needle.getAsync(url, options);
}).then((res) => {
console.log(Object.keys(res))
console.log(res[0].socket.servername);
console.log(res[1].socket.servername)
console.log(res[2].socket.servername)
}).catch((err)=>{
console.log(err)
})
bluebird promise를 사용하지 않고 구현하면 다음과 같습니다.
for(i in urls){
needle.get(i,options,(err,res,body)=>{
if(err){
console.log(err);
return
}
console.log(res);
})
}
needl.get이라는 비동기 함수를 사용해 구현할 수 있습니다.
하지만 promise로 구현하는 것이 좋습니다.
위의 예시는 프로세스가 간단해 괜찮지만 구조가 복잡해지면 콜백 지옥에 빠질 수 있습니다.
728x90
'기타 > node js' 카테고리의 다른 글
[Node js] mysql 연동하기 (0) | 2020.12.18 |
---|---|
자바스크립트 비동기 promise, 콜백함수 예제 (0) | 2020.12.09 |
nodejs bluebird promisify 예제 (0) | 2020.12.03 |
nodejs mysql 연동하기 (0) | 2020.12.02 |
자바스크립트 프로미스(Javascript Promise) then catch에 대해 알아보자. (0) | 2020.11.29 |