Table of Content
이 글은 Node.js 교과서(조현영 저)
라는 책으로 공부한 내용을 정리한 글입니다.
const, let
- var는 이제 const와 let이 대체. 블록과 관계없이 접근 가능
- const와 let은 블록 스코프를 가지므로 블록 밖에선 접근 불가
- const는 다른 값을 대입할 수 없지만 let은 다른 값을 대입할 수 있음
템플릿 문자열
- 백틱
- 형식:
${VAR_NAME}
const hello = '안녕요?ㅎ' console.log(`hello: ${hello}`); // 출력 결과: hello: 안녕요?ㅎ
객체 리터럴
- 함수:
oldFunc: function() { }
->newFunc() { }
- 속성명과 변수명이 겹치는 경우 한 번만 써도 됨:
oldObj = { sayNode: sayNode, }
->newObj = { sayNode, }
화살표 함수
=>
기호로 선언. return 생략 가능.
const add = (x, y) => return x + y;
const add = (x, y) => x + y;
this 키워드를 재결합(rebind) 하지 않으므로 this를 참조하는 별도의 변수를 생성할 필요가 없음
비구조화 할당
객체
const data = {
status: { name: 'node', },
getName() { return status.name; }
}
const { status } = data; // status <- data.status
const { status: { name } } = data; // name <- data.status.name
const { getName } = data; // getName() <- data.getName()
배열
var array = ['nodejs', {}, 1, true];
const [node, obj, , bool] = array;
프로미스
기본 구조
const condition = true;
const promise = new Promise((resolve, reject) => {
if (condition) resolve('성공'); // resolve -> then
else reject('실패'); // reject -> catch
});
promise
.then((message) => { console.log(message); })
.catch((error) => { console.log(error); });
여러 개의 then
promise
.then((message) => { // 이전 then의 리턴 값을
return new Promise((resolve, reject) => { resolve(message); });
}) // 다음 then이 받음
.then((message2) => { console.log(message2); })
.catch((error) => { console.log(error); });
프로미스 여러 개 실행하기
Promise.all()
메서드 사용
const promise1 = Promise.resolve('성공1'); // 즉시 resolve하는 프로미스 객체 생성
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
.then((result) => { console.log(result); }) // 프로미스가 모두 resolve될 때
.catch((error) => { console.error(error); }); // 프로미스가 적어도 하나 reject될 때