반응형
# 자바스크립트_화살표 함수
- this를 사용할 경우 function을 사용 / 그게 아니라면 모두 화살표 함수로 통일. (권장)
# 상황1
function add1(x, y) {
return x + y;
}
1. 화살표 함수 사용
const add2 = (x, y) => {
return x + y;
};
2. 중괄호 다음 바로 return 나오면 아래와 같이 생략 가능.
const add3 = (x, y) => x + y;
2-1. return 값을 괄호로 묶어줌
const add4 = (x, y) => (x + y);
3. 객체를 return 하는경우 소괄호 필수!
const obj = {x, y} => ({x, y})
# 상황2
function not1(x) {
return !x;
}
1. 매개변수가 1개, 중괄호 다음 바로 return 나오는 경우
const not2 = x => !x;
- 화살표 함수는 function을 완벽히 대체할 수 없음. (this 때문)
var relationship1 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends: function () {
var that = this; // relationship1을 가리키는 this를 that에 저장
this.friends.forEach(function (friend) {
console.log(that.name, friend);
});
},
};
relationship1.logFriends();
= function에서 this를 다른 함수에서 사용하기 위해선 that 등을 사용해야 함.
(function은 자신만의 this를 가짐)
화살표 함수 사용
const relationship2 = {
name: 'zero',
friends = ['nero', 'hero', 'xero'],
logFriends() {
this.friends.forEach(friend => {
console.log(this.name, friend);
});
}
};
relationship2.logRfiends();
= 화살표 함수는 자신만의 this를 갖지 않고, 무조건 부모 function의 this를 물려받음.
# 자바스크립트_비구조화 할당(구조분해 할당)
- 구조분해 문법 (배열, 객체)
1. 객체 구조 분해 문법 예시
const example = {a: 123, b: {c: 135, d: 146}}
const a = example.a;
const d = example.b.d;
# 구조 분해 문법(객체) // 객체는 키가 정확히 일치해야 함.
const {a, b: { d}} = example;
console.log(a); // 123
console.log(d); // 146
2. 배열 구조 분해 문법 예시
arr = [1, 2, 3, 4, 5]
const x = arr[0]
const y = arr[1]
const z = arr[4]
# 구조 분해 문법(배열) // 배열은 자리가 동일해야 함.
const [x, y, , , z] = arr; // 자릿수 맞춰주는 것
- this를 사용하고 있는 경우 구조분해 할당 시 문제 발생
const candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy() {
this.status.count--;
return this.status.count;
},
};
const { getCandy, status: { count }} = candyMachine;
# 자바스크립트_클래스
- 클래스는 프로토타입이다. 프로토타입의 문법을 깔끔하게 만들어 주는 것. (Constructor(생성자), Extends(상속) 등을 깔끔하게 처리할 수 있다. / 코드가 그룹화되어 가독성이 향상된다.)
# 이전 클래스 문법(생성자 함수)
var Human = function(type) {
this.type = type || 'human';
};
Human.isHuman = function(human) {
return human instanceof Human;
}
Human.prototype.breathe = function() {
alert('h-a-a-a-m');
};
var Zero = function(type, firstName, lastName) {
Human.apply(this, arguments);
this.firstName = firstName;
this.lastName = lastName;
};
Zero.prototype = Object.create(Human, prototype);
Zero.prototype.constructor = Zero; // 상속하는 부분
Zero.prototype.sayName = fuunction() {
alert(this.firstName + ' ' + this.lastName);
};
var oldZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(oldZero); // true
# 변경 클래스 문법
Class Human {
constructor(type = 'human') {
this.type = type;
}
static isHuman(human) {
return human instanceof Human;
}
breathe() {
alert('h-a-a-a-m');
}
}
Class Zero extends human {
constructor(type, firstName, lastName) {
super(type);
this.firstName = firstName;
this.lastName = lastName;
}
}
sayName() {
super.breathe();
alert('${this.firstName} ${this.lastName}');
}
const NewZero = new Zero('human', 'Zero', 'Cho');
# 자바스크립트_Promise, async/await
## 자바사크립트 프로미스(Promise)
- 콜백 헬이라고 불리는 지저분한 자바스크립트 코드의 해결책이다.
- 프로미스 : 내용이 실행 되었지만, 결과를 아직 반환하지 않은 객체
- Then을 붙이면 결과를 반환함
- 실행이 완료되지 않았으면 완료된 후 Then 내부 함수가 실행된다.
- Resolve (성공리터값) -> then 으로 연결
- Reject (실패리턴값) -> catch로 연결
- Finally 부분은 무조건 실행된다.
# 프로미스 사용 시 코드 분리 가능.
const promise = setTimeoutPromise(3000)
console.log('다른업무');
console.log('다른업무');
console.log('다른업무');
console.log('다른업무');
console.log('다른업무');
promist.then(() => {
지금 실행.
});
- Promise.all(배열) : 여러 개의 프로미스를 동시에 실행. 하나라도 실패하면 catch로 감. allSettled로 실패한 것만 추려낼 수 있다.
## 자바스크립트 에이싱크/어웨잇(async/await)
- 변수 = await 프로미스; 인 경우 프로미스가 resolve된 값이 변수에 저장(await이 then 역할)
- 변수 await 값; 인 경우 그 값이 변수에 저장
- async/await의 실행 순서는 오른쪽에서 왼쪽방향임.
async function findAndSaveUser(Users) {
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({ gender : 'm' });
// 생략
}
async에서 return한 경우 무조건 then으로 받아야 함. (async도 프로미스임)
const promise = new Promise(...)
promise.then((result) => ...)
async function main() {
const result = await promise;
return result;
}
main().then((name) => ...) 또는 const name = await main() 가능.
async/await의 경우 result만 있고, reject를 처리할 수 있는 부분이 없어서
reject를 처리하기 위해 try~catch를 사용해야함
async function main() {
try{
const result = await promise;
return result;
} catch (error) {
console.error(error);
}
}
- for await (변수 or 프로미스 배열) : 노드 10부터 지원, resolve된 프로미스가 변수에 담겨 나온다. await을 사용하기 때문에 async 함수 안에서 해야함 (프로미스 반복 시 사용)
const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
(async () => {
for await (promise of [promise1, promise2]) {
console.log(promise);
}
})();
반응형
'인프런 강의 학습 > Node.js 교과서' 카테고리의 다른 글
Node.js 학습_노드 내장모듈 (0) | 2021.10.03 |
---|---|
Node.js 학습_REPL 사용 / JS파일 실행 / 모듈 생성 / 노드 내장 객체 (0) | 2021.10.02 |
Node.js 학습_자바스크립트 문법(호출 스택 / 이벤트 루프 / const, let / 템플릿 문자열, 객체 리터럴) (0) | 2021.09.30 |
Node.js 학습_노드 설치 / VS Code 설치 (0) | 2021.09.30 |
Node.js 학습_노드의 정의 / 런타임 / 노드 내부구조 / 이벤트 기반 / 논블로킹 (0) | 2021.09.30 |