Javascript에서 변수 선언할 때 쓰였던 var는 이제 const 와 let으로 대체 되었다.
-
var과 const, let의 차이점
-
var은 함수 스코프를 가지고 const와 let은 블록 스코프를 사용한다.
- 블록의 범위는 if, while, for, function 등의 중괄호이다. 따라서 블록 범위 밖에서는 사용할 수 없다.
-
-
const와 let의 차이점
-
const는 한 번 대입하면 다른 값을 대입할할 수 없습니다.(초기화 시 값을 대입하지 않으면 에러 발생)
- let은 초기화 했던 변수에 다른 값을 대입해야하는 경우에 사용
-
큰, 작은따옴표로 감싸는 기존 문자열과는 다르게 백틱으로 감싸는 새로운 문자열이 생겼다.
-
ex) `${var1} 더하기 ${var2}는 '${result2}'`; //1 더하기 2는 '3'
객체 리터럴에 편리한 기능들이 추가되었다.
const sayNode = {
console.log('Node');
};
const ex = 'ES';
/*
var oldObject = {
sayJS: function(){
console.log('JS');
}.
sayNode: sayNode,
};
oldObject.[es + 6] = 'Fantastic';
oldObject.sayNode(); //Node
oldObject.sayJS(); //JS
console.log(oldobject.ES6); //Fantasitc
*/
const newObject = {
sayJS(){ //기존에는 sayJS: function(){ 이였지만 간단해졌다.
console.log('JS');
},
sayNode, // 기존에는 sayNode: sayNode - 이처럼 속성명과 변수명이 겹치는 경우에는 한 번만 쓸 수 있게 간단해 졌다.
[es + 6]: 'Fantastic', // 변수를 활용하여 속성이름을 설정할 때 위 oldObject와 같이 변수 밖에서 하던 것을 변수 안에서 바로 만들 수 있게 되었다.
};
newObject.sayNode(); //Node
newObject.sayJS(); //JS
console.log(newObject.ES6); //Fantastic
화살표 함수
//#1
function add1(x, y){
return x+y;
}
//#2
const add2 = (x, y) => {
return x+y;
}
//#3
const add3 = (x, y) => x+y;
// add1,add2,add3은 같은 기능을 하는 함수
기존의 function과 다름 점은 this 바인드 방식이다.
//기존
var relationship1={
name: 'zero'
friend: ['nero', 'hero', 'xero'],
logFriends: function(){
var that =this; // relationship1을 가리키는 this를 that이라는 변수에 저장
this.friends.forEach(function(friend){
console.log(that.name, freind);
});
},
};
relationship1.logFriends();
//새로운
const relationship2 ={
name = 'zero',
friend: ['nero', 'hero', 'xero'],
logFriends(){
this.friends.forEach(friend => { // 화살표 함수를 사용하여 상위 스코프의 this를 그대로 물려받아 사용이 가능해졌다.
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
비구조화 할당
const candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy() {
this.status.count--;
return this.status.count;
}
};
const { getCandy, status: {count} }= candyMachine; //candyMachine 객체 안의 속성을 찾아서 변수와 배칭해준다.
/*
다른 예시
const array = ['nodejs',{},10,true];
const [node,obj, ,bool] = array;
*/
프로미스
Javascript와 노드에서는 주로 비동기 프로그래밍을 한다. 특히 이벤트 주도 방식 때문에 콜백 함수를 자주 사용한다.
const condition = true;
const promist = new Promise((resolve, reject) =>{
if(condition){
resolve('성공');
}else{
reject('실패');
}
});
promise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
});
/*
프로미스를 사용하려면 먼저 객체를 생성해아한다.
객체를 생성할 때 resolve와 reject를 매개변수로 갖는 콜백함수를 넣어주고
만들어진 객체에는 then과 catch 메서드를 붙일 수 있다.
resolve가 호출되면 then이 실행되고 reject가 호출되면 catch가 호출된다.
*/
promise
.then((message) => {
console.log(message);
return new Promise((resolve, reject) => {
resolve(message)
});
})
.then((message2) => {
console.log(message2);
return new Promise((resolve, reject) => {
resolve(message2);
});
})
.catch((error) => {
console.error(error);
});
//then이나 catch에서 다시 또 then이나 catch를 붙일 수 있다.
//이전 then에서 return 해준 resolve값을 return 해주었으므로 message값이 message2로 전달된다.
async/await
프로미스가 콜백 지옥을 해결했다지만, 여전히 코드가 장황하다. async/await 문법을 사용하면 보다 더 깔끔하게 코드를 줄여준다.
function findAndSaveUser(Users) {
Users.findOne({})
.then((user) => {
user.name = 'zero';
return user.save();
})
.then((user) =>{
return Users.findOne({gender: 'm'});
})
.then((user) =>{
//생략
})
.catch(err =>{
console.error(err);
});
}
/////////////////////////////////////////////////////////////////////////
async function findAndSaveUser(Users){ //const findAndSaveUser = async(Users)=>{ 으로도 바꿀 수 있다.
try{
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({gender: 'm'});
//생략
}catch(error){
console.error(error);
}
}
/*
function 앞에 async를 붙여주고 프로미스 앞에 await를 붙여주어 해당 프로미스가 resolve될 때 까지
기다린 뒤 다음 로직으로 넘어간다.
위에서는 awit Users.findeOne({})이 resolve될 때까지 기다린 뒤, user 변수를 초기화하는 것이다.
*/
References
- Node.js 교과서 /조현영 지음/길벗출판사
'Javascript > Node.js' 카테고리의 다른 글
요청과 응답 이해하기(서버구현) (0) | 2019.10.19 |
---|---|
버퍼와 스트림 이해하기 (0) | 2019.10.17 |
파일 시스템 접근하기 (0) | 2019.10.10 |
모듈 만들기 (0) | 2019.10.10 |
Front end Javascript (0) | 2019.10.04 |
댓글