[Node.js教科書]ES 2015+
ES2015+
const, let
if (true) {
var x = 3;
}
console.log(x); // 3
if (true) {
const y = 3;
}
console.log(y); // y is not defined
if (true) {
var x = 3;
}
console.log(x); // 3
if (true) {
const y = 3;
}
console.log(y); // y is not defined
const a = 0;
a = 1; // Uncaught TypeError: Assignment to constant variable.
let b = 0;
b = 1; // 1
const c; // Uncaught SyntaxError: Missing initializer in const declaration.
テンプレート文字列
var num1 = 1;
var num2 = 2;
var result = 3;
var string = num1 + ' 더하기 ' + num2 + '는 ' + result;
// 백틱 사용
const num1 = 1;
const num2 = 2;
const result = 3;
const string = `${num1} 더하기 ${num2}는 ${result}`; // 따옴표 함께 사용 가능
オブジェクト範囲の
以前の文法
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
ES6const sayNode = function() {
console.log('Node');
};
const es = 'ES';
const newObject = {
sayJS() {
console.log('JS');
},
sayNode,
[es + 6]: 'Fantastic',
};
newObject.sayNode(); // Node
newObject.sayJS(); // JS
console.log(newObject.ES6); // Fantastic
矢印関数
// add1 == add2 == add3 == add4
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); // 가독성을 위해 소괄호 사용
// not1 == not2
function not1(x) {
return !x;
}
const not2 = x => !x; // 매개변수 하나일 경우
このバインド方法var relationship1 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends: function () {
var that = this; // relationship1을 가리키는 this를 that에 저장. 간접적 접근
// that 할당 안될시 접근 불가
this.friends.forEach(function (friend) {
console.log(this.name, friend);
});
},
};
relationship1.logFriends();
// 화살표 함수
const relationship2 = {
name: 'zero',
friends: ['nero', 'hero', 'xero'],
logFriends() { // 화살표 함수 사용으로 상위 스코프 this 물려받음
this.friends.forEach(friend => {
console.log(this.name, friend);
});
},
};
relationship2.logFriends();
既定では矢印関数が使用されます.このオプションを使用する必要がある場合は、構造分解の割り当て
オブジェクトや配列から属性や要素を簡単に抽出できます.
既存のオブジェクトコード
var candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy: function () {
this.status.count--;
return this.status.count;
},
};
var getCandy = candyMachine.getCandy;
var count = candyMachine.status.count;
オブジェクト構造分解割り当ての使用const candyMachine = {
status: {
name: 'node',
count: 5,
},
getCandy() {
this.status.count--;
return this.status.count;
},
};
const { getCandy, status: { count } } = candyMachine;
◆オブジェクトの属性を検索し、変数と一致させます.ただし、関数のthisは変更される可能性があるのでbind関数を使用してthisの元の値に変更します.アレイの構造分解の割り当て
var array = ['nodejs', {}, 10, true];
var node = array[0];
var obj = array[1];
var bool = array[3];
const array = ['nodejs', {}, 10, true];
const [node, obj, , bool] = array;
3番目の要素には変数の名前が付けられていないため、10は無視されます.カテゴリ
プロトタイプベースの構文を美しいクラスに変換
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');
Human.isHuman(newZero); // true
保証する
すぐに実行されますが、欠品値が受信されたオブジェクト
const condition = true; // true면 resolve, false면 reject
const promise = new Promise((resolve, reject) => {
if (condition) {
resolve('성공');
} else {
reject('실패');
}
});
// 다른 코드가 들어갈 수 있음
promise
.then((message) => {
console.log(message); // 성공(resolve)한 경우 실행
})
.catch((error) => {
console.error(error); // 실패(reject)한 경우 실행
})
.finally(() => { // 끝나고 무조건 실행
console.log('무조건');
});
コールバック関数、プロセスの比較// 콜백 사용
function findAndSaveUser(Users) {
Users.findOne({}, (err, user) => { // 첫 번째 콜백
if (err) {
return console.error(err);
}
user.name = 'zero';
user.save((err) => { // 두 번째 콜백
if (err) {
return console.error(err);
}
Users.findOne({ gender: 'm' }, (err, user) => { // 세 번째 콜백
// 생략
});
});
});
}
// 프로미스 사용
function findAndSaveUser(Users) {
Users.findOne({}) // then 메서드 순차적 실행
.then((user) => {
user.name = 'zero';
return user.save();
})
.then((user) => {
return Users.findOne({ gender: 'm' });
})
.then((user) => {
// 생략
})
.catch(err => { // 콜백에서 따로 처리해야 했던 에러도 마지막 catch에서 한번에 처리
console.error(err);
});
}
Promise.allconst promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
.then((result) => {
console.log(result); // ['성공1', '성공2'];
})
.catch((error) => {
console.error(error);
});
*すべてが解決するまで待って、それから行きました.promis結リンゴ値はresultパラメータに入れられる.拒否されたものがあればcatchに移動しますasync/await
プロミスはcallback地獄を解決したが、コードは依然として冗長だ.
async関数を置き換えた後に「事前待機」を付けると、プロセスの解決を待機し、次の論理に進みます.
async function findAndSaveUser(Users) {
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({ gender: 'm' });
// 생략
}
try/catchエラー処理がないためtry/catchを使用
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);
}
};
for文系async/awaitconst promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
(async () => {
for await (promise of [promise1, promise2]) {
console.log(promise);
}
})();
ES 2018文法.プロセスを順番に実行できますソース
Node.教科書
Reference
この問題について([Node.js教科書]ES 2015+), 我々は、より多くの情報をここで見つけました https://velog.io/@devbin20/Node.js-교과서-ES2015テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol