-
Async 모듈을 이용한 비동기 처리NodeJS 2019. 5. 26. 14:46
얼마전 Node에서 비동기 처리를 순서대로 처리해야 하는 일이 있었다.
구글을 검색하다 async.waterfall in a For Loop in Node.js을 찾았다.
var async = require("async") var users = []; // Initialize user array or get it from DB async.forEachLimit(users, 1, function(user, userCallback){ async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' console.log('done') userCallback(); }); }, function(err){ console.log("User For Loop Completed"); });
async는 async, await인줄 알았는데, 비동기 처리에 사용하는 모듈 이었다.
70 여 가지 모듈을 지원하며, 예제도 잘 나와 있다.
이중 제어 관련하여 다음의 매소드 등이 제공된다.
- XXXLimit : 한번에 처리 하는 Worker 갯수 지정
- XXXSeries : 한개씩 처리
- waterfall : 여러 비동기 처리를 순차적으로 처리
- parallel : 콜렉션을 병렬 처리
- apply : 인수 처리
- map : 새로운 컬렉션을 생성
이 외에도 많은 기능이 제공된다.
Async provides around 70 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your asynchronous function -- a callback which expects an Error as its first argument -- and calling the callback once.
비동기 처리를 할때 사용하면 상당히 유용하다.
참고 자료
'NodeJS' 카테고리의 다른 글
puppeteer에서 POST로 요청 날리기 (0) 2019.07.07 nodejs를 이용하여 web push 몇가지 주요 사항 (0) 2019.07.06 nodejs에서 request Body에 json 처리 & body 크기 제한 (0) 2019.02.06 Node 모듈 설치시 오류시 해결 방법 (1) 2019.02.06 pm2 cluster mode 특징 (0) 2019.02.06