안녕세계

[SK고용디딤돌] Node.js (3/10) - 6주차 본문

[SK고용디딤돌] Node.js (3/10) - 6주차

Junhong Kim 2016. 8. 8. 18:20
728x90
반응형

project

├app.js

│         (dependencies 의존성)

├node_modules 노드 확장 모듈

└package.json프로젝트에 대한 정보


※ package.json

- 프로젝트에 대한 정보를 담고있다.

- 확장모듈의 의존성에 대한 정보를 관리한다.

- npm init 명령어를 이용해서 만들 수 있다.


※ npm install [module_name] --save 옵션

- package.json 의 dependencies에 확장 모듈 정보를 추가해준다.



※ package.json의 dependency에 있는 정보를 읽어서 npm 라이브러리를 설치할 수 있다.



< nodemon >

npm install nodemon -g

변경하고 나면 다시 프로그램을 실행해야하는데 nodemon 명령어를 이용하면 변경하고 저장하고 실행까지 해줌.




< 콜백 >

- 에러났을때 err 콜백

- 실행 정상일때 run 콜백

- 특정 시저에 호출되는 콜백


비동기 함수를 순차적으로 수행하는 방법 -> 콜백을 사용



< 콜백지옥을 해결하는 방법 - async >


npm install async@1.5 --save 버전 지정해서 다운로드 하기


<async.each>

async.each(collection, iteratiorFunc, doneCallback)
                                  ↓
                               callback()

* 비동기적(parallel)으로 수행
var async = require('async');

var arr = [1, 2, 'three', 4, 5];

async.each(arr, function(item, callback) {
if (typeof(item) !== 'number') {
callback(new Error(item + ' is not a number!!! '));
} else {
console.log(item);
callback();
}
}, function(err) {
if (err) {
console.log(err);
} else {
console.log('completed!!!');
}
});
collection 비동기적으로 호출됨, 에러가 발생하도 다른데 영향을 주지 않음.


* 직렬적(series) 으로 수행
async.eachSeries(arr, function(item, callback) {
if (typeof(item) !== 'number') {
callback(new Error(item + ' is not a number!!! '));
} else {
console.log(item);
callback();
}
}, function(err) {
if (err) {
console.log(err);
} else {
console.log('completed!!!');
}
});

< async.series(tasks, doneCallback); >


task에는 배열이 들어간다.

var async = require('async');

var x = 0;

async.series([ // series 는 순차적으로 실행 된다.
function(cb) {
var result = ++x;
console.log(result);
cb(null, result);
},
function(cb) {
var result = ++x;
console.log(result);
cb(new Error('그냥 에러'));
//cb(null, result);
},
function(cb) {
var result = ++x;
console.log(result);
cb(null, result);
}
], function(err, results){
if(err) {
console.log(err);
} else {
console.log(results);
}
});

< async.parallel(tasks, doneCallback); >

var async = require('async');

var x = 0;

async.parallel([ // parallel 는 병행적으로 실행 된다.
function(cb) {
var result = ++x;
console.log(result);
cb(null, result);
},
function(cb) {
var result = ++x;
console.log(result);
cb(new Error('그냥 에러'));
//cb(null, result);
},
function(cb) {
var result = ++x;
console.log(result);
cb(null, result);
}
], function(err, results){
if(err) {
console.log(err);
} else {
console.log(results);
}
});

< async.waterfall(tasks, doneCallback); >

var async = require('async');

async.waterfall([
function(cb) {
var a = 10;
cb(null, a);
},
function(arg1, cb) {
var b = 20;
cb(null, arg1, b);
},
function(arg1, arg2, cb) {
var c = 30;
cb(null, arg1 + arg2 + c);
}
], function(err, result) {
console.log(result);
});

< async.whilst(tasks, doneCallback); >

var async = require('async');

var count = 0;
async.whilst(
function() {
return count < 5;
},
function(callback) {
count++;
setTimeout(function() {
callback(null, count);
}, 1000);
},
function (err, n) {
console.log(n);
}
);

< async.map >

- each와 동일하지만 차이점은 콜백에 매개변수가 존재한다.

- 컬렉션에 있는 각각 n개의 데이터들을 꺼내서 n개의 변형된 데이터를 만든다

- 데이터를 분류할 떄 보통 사요한다. 

var async = require('async');

async.map(arr, function(item, callback) { // iterate function (원소 하나하나에 적용될 function)
if(typeof(item) !== 'number') {
callback(new Error(item + ' is not a number!!!'))
} else {
console.log(item);
callback(null, {'category' : item % 2, 'values' : item});
}
}, function(err, results) { // 모두 끝냈을 때의 function
if(err) {
console.log(err);
} else {
console.log(results);
}
});


< async.reduce >

var async = require('async');

async.reduce([1,2,3], 0, function(memo, item, callback) {
// pointless async:
process.nextTick(function() {
callback(null, memo + item)
});
}, function(err, result) {
// result is now equal to the last value of memo, which is 6
});


728x90
반응형
Comments