Node.js 2장
const, let
- var 대체
if (true) {
var x = 3;
}
console.log(x); // 3
if (true) {
const y =3;
}
console.log(y); // error
x는 정상출력, y는 에러 발생
- var => 함수 스코프를 가지므로 블록과 관계없이 접근이 가능
- const, let => 블록스코프를 가지므로 블록 밖에서는 변수에 접근 X
const a = 0;
a = 1; // error
let b = 0;
b = 1; // 1
- const는 한 번 대입하면 다른 값을 대입할 수 없음
- 변수 선언시에는 const, 다른 값을 대입해야 할 때는 let 사용
템플릿 문자열
const num3 =1;
const num4 = 2;
const result2 = 3;
const string2 = '${num3} 더하기 ${num4}는 '${result2}'';
console.log(string2); // 1더하기 2는 '3'
- ${변수} 형식으로 변수를 기호 없이 문자열에 넣을 수 있음
객체 리터럴
ES5
var sayNode = function() {
console.log('Node');
};
var es = 'ES';
var oldObject = {
sayJS : function() {
console.log('JS');
},
sayNode: sayNode,
};
oldObject[es + 6] = 'Fantastic';
oldObject.sayNode(); // Node
oldObject.sayJS(); // JS
console.log(oldObject.ES6); // Fantastic
ES6
const newObject = {
sayJS() {
console.log('JS');
},
sayNode,
[es + 6]: 'Fantastic',
};
newObject.sayNode(); // Node
newObject.sayJS(); // JS
console.log(newObject.ES6); // Fantastic
- sayJS와 같은 객체의 메서드에 함수를 연결할 떄 콜론, function을 붙이지 않아도 됨
- 속성명과 변수명이 겹치는 경우 한 번만 쓰면됨
- 객체의 속성을 동적으로 생성할 수 있음
화살표 함수
function add1 (x, y){
return x + y;
}
const add2 = (x, y) => {
return x + y;
};
const add3 = (x, y) => x + y;
const add4 = (x, y) => (x + y);
- add 1,2,3,4는 모두 같은 기능을 하는 함수
function not1(x) {
return !x;
}
const not2 = x => !x;
- not 1,2도 같은 기능을 하는 함수
- 화살표 함수에서는 function 선언 대신 "=>" 기호로 함수를 선언한다.
- 변수에 대입하면 나중에 재사용이 가능하다.
- return문을 줄일 수 도 있다
비구조화 할당 (다시보기)
- 객체와 배열로부터 속성이나 요소를 쉽게 꺼낼 수 있음
const candyMachine = {
status : {
name : 'node',
count : 5,
},
getCandy() {
this.status.count--;
return this.status.count;
}
};
const { getCandy, status: { count } } = candyMachine
- candyMachine 객체 안의 속성을 찾아서 변수와 매칭해준다.
- count 처럼 여러 단계 안의 속성도 찾을 수 있다.
프로미스 (다시보기 ㅠㅠ)
const condition = true;
const promise = new Promise(resolve, reject) => {
if (condition) {
resolve('성공');
} else {
reject ('실패');
}
});
promise
.then ((message_ => {
console.log(message); // 성공한 경우 실행
})
.catch((error) => {
console.error(error); // 실패한 경우 실행
});
- 비동기 처리 => 특정 코드의 실행이 완료될때까지 기다리지 않고 다음 코드를 먼저 수행하는
자바스크립트의 특성
- new promise로 프로미스를 생성한 후 안에 resolve와 reject를 매개변수로 갖는 콜백 함수를 넣어준다
이렇게 만든 promise 변수에 then과 catch 메서드를 붙일 수 있다.
- 프로미스 내부에서 resolve가 호출되면 then이 실행되고 reject가 호출되면 catch가 실행된다.
- resolve와 reject에 넣어준 인자는 각각 then과 catch의 매개변수에서 받을 수 있다.
promise
.then((message) => {
return new Promise((resolve, reject) => {
resolve(message); });
})
.then((message2) => {
console.log(message2);
return new Promise((resolve, reject) => {
resolve(message2);
});
})
.then((message3) => {
console.log(message3);
})
.catch((error) => {
console.error(error);
});
- 콜백을 프로미스로 바꿀 수 있음
- 프로미스 부분 더 공부하기
'Node.js' 카테고리의 다른 글
REST API (0) | 2019.12.04 |
---|---|
npm과 npx (0) | 2019.12.04 |
Node.js 4장 (0) | 2019.11.27 |
Node.js 3장 (0) | 2019.11.27 |
Node.js 1장 (0) | 2019.11.23 |