백엔드 Back-end/노드 Node.js

Node.js async 모듈, 자주 쓰는 코드

Tap to restart 2020. 10. 23. 18:00
반응형

참고:  async documentation

 

Node.js로 개발하다보면 가장 자주 쓰는 모듈이다.

주로 순차처리가 필요할 때 자주 쓴다.

eachSeries

The same as each but runs only a single async operation at a time.

each와 같지만 한번에 하나의 비동기 작업만 실행한다.

const async = require("async");
const cities = ["서울", "부산", "대구", "대전", "울산", "인천"];

async.eachSeries(cities, function (city, callback) {
    console.log('city:' + city);
    callback(null);
}, function (err) {
    if (err) console.error(err.message);
    console.log('eachSeries end');
});

결과

city:서울
city:부산
city:대구
city:대전
city:울산
city:인천
eachSeries end

 

waterfall

폭포: 순차 처리한다.

const async = require("async");
async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        console.log("arg1", arg1);
        console.log("arg2", arg2);
        callback(null, 'three');
    },
    function(arg1, callback) {
        console.log("arg1", arg1);
        callback(null, 'done');
    }
], function (err, result) {
    console.log("result", result);
});

결과

arg1 one
arg2 two
arg1 three
result done

 

 

 

const async = require("async");
async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        console.log("async1 arg1", arg1);
        console.log("async1 arg2", arg2);
        callback(null, 'three');
    },
    function(arg1, callback) {
        console.log("async1 arg1", arg1);
        callback(null, 'done');
    }
], function (err, result) {
    console.log("async1 result", result);
});

//함수를 사용한 예
async.waterfall([
    myFirstFunction,
    mySecondFunction,
    myLastFunction,
], function (err, result) {
    console.log("async2 result", result);
});
function myFirstFunction(callback) {
    callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
    console.log("async2 arg1", arg1);
    console.log("async2 arg2", arg2);
    callback(null, 'three');
}
function myLastFunction(arg1, callback) {
    console.log("async2 arg1", arg1);
    callback(null, 'done');
}

결과

async1 arg1 one
async1 arg2 two
async2 arg1 one
async2 arg2 two
async1 arg1 three
async2 arg1 three
async1 result done
async2 result done

nodejs 특성 때문에 첫 번째 async waterfall과 두 번째 async waterfall 결과가 섞여서 나온다.

반드시 첫 번째 waterfall 다음 두 번째 waterfall이 실행되게 하려면 위 예의 경우 waterfall안에 waterfall을 써야 한다.

반응형