[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
  • var:関数スケール付き.
  • if文ブロックの制限を受けない
  • const:blockscope.ブロック外では変数にアクセスできません.定数.1回割り当てた後に別の値X
  • を割り当てる.
  • let:ブロックスキャン.
  • 他の値を割り当てる必要がある場合に使用
    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
    ES6
    const 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
  • コロンで、機能は必要ありません.
  • 属性名と変数名が同じで、1回で
  • 以前の構文はオブジェクト文字以外で動的に生成され、ES 6はオブジェクト文字内で属性
  • を動的に宣言する.

    矢印関数

    // 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.all
    const 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に移動します
  • Promise.拒否:すぐに拒否
  • Promise.resolve:直ちにresolve
  • 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/await
    const promise1 = Promise.resolve('성공1');
    const promise2 = Promise.resolve('성공2');
    (async () => {
      for await (promise of [promise1, promise2]) {
        console.log(promise);
      }
    })();
    ES 2018文法.プロセスを順番に実行できます

    ソース


    Node.教科書