TIL#121:[JavaScriptで]非同期呼吸処理(2):Promise


JavaScriptエンジンは単一スレッドです.したがって、2つの操作を同時に行うことはできず、複数の操作が同時に要求されたときに前の操作の完了を待つ.

Promise?



基本概念

  • オブジェクト
  • 非同期のシンプル化を支援
  • コールバック関数処理の構造からnew Promise()、resolve()およびthen()
  • に変換できる.

    Promise State

  • デフォルトでは、プロセスには3つのステータス(プロセス)があります.
    ++pending-非同期処理ロジックはまだ完了していません
    ++完了-非同期処理が完了すると、プロセスは完了した場合に結果値を返します.処理結果値はthen()で取得できます
    ++refered-非同期処理に失敗したり、エラーが発生したりします.catch()でエラーを制御できる(できるだけ.catch()でエラーをキャプチャできる)
  •     new Promise(); // pending state
        
        new Promise(function(resolve, reject) {
        	
        }); // new Promise method with callback function
        
        new Promise(function(resolve, reject) {
        	resolve();
        }); // fulfilled state
    
    	function getDate() {
        	return new Promise(function (resolve, reject) {
            	var data = 100;
              	resolve(data);
            }); 
        }; // .then()으로 처리 결과값 받음
    	
    	getData().then(function (resolvedData) {
        	console.log(resolvedData);
        }); // 100
    
        new Promise(function (resolve, reject) {
          reject();
        }); // rejected state
    
        function getData() {
          return new Promise(function (resolve, reject) {
            reject(new Error('Failed'));
          });
        }; 
    
        getData().then().catch(function(err){
          console.log(err)
        }) // reject()의 결과값을 받음

    Promise Example

    var timeAttack = new Promise(function (resolve, reject) {
      setTimeout(function () {
        var ran = Math.random() * 10;
        if (ran >= 5) {
          resolve(ran);
        } else {
          reject(new Error('Failed'));
        }
      }, 3000);
    });
    
    
    timeAttack.then(function (num) {
      console.log(num + ' complete!');
    }, function () {
      console.log('error');
    }) // then의 두번째 인자로 에러 핸들링
    
    timeAttack.then(function (num) {
      console.log(num + ' complete!')
    }).catch(function (err) {
      console.log(err);
    }); // .catch()으로 에러 핸들링
    
    
  • プロミス客体の後ろにあります.そして()タスク実行結果値
  • .エラーハンドルはcatch()
  • Promise Chaining

    var timeAttack = new Promise(function (resolve, reject) {
      setTimeout(function () {
        var ran = Math.floor(Math.random() * 10);
        if (ran >= 5) {
          resolve(ran);
        } else {
          reject(new Error('Failed'));
        }
      }, 1000);
    });
    
    timeAttack
      .then(function (num) {
        console.log(num)
        return num + 10 
      }) // 7
      .then(function (num) {
        console.log(num)
        return num + 100 
      }) // 17
      .then(function (num) {
        console.log(num)
      }) // 117

    finally?

  • Promiseの処理が完了すると、指定したコールバック関数
  • が実行されます(満たされているかどうかにかかわらず、拒否されています).
  • が正常に実行または拒否されたかどうかにかかわらず、Promise処理後にコードは
  • を1回実行する必要があります.
    finallyサンプルコード
    let isLoading = true;
    
    fetch(myRequest).then(function(response) {
        var contentType = response.headers.get("content-type");
        if(contentType && contentType.includes("application/json")) {
          return response.json();
        }
        throw new TypeError("Oops, we haven't got JSON!");
      })
      .then(function(json) { /* process your JSON further */ })
      .catch(function(error) { console.log(error); })
      .finally(function() { isLoading = false; });
    上のコード
    var timeAttack = new Promise(function (resolve, reject) {
      setTimeout(function () {
        var ran = Math.floor(Math.random() * 10);
        if (ran >= 5) {
          resolve(ran);
        } else {
          reject(new Error('Failed'));
        }
      }, 1000);
    });
    
    timeAttack
      .then(function (num) {
        console.log(num)
        return num + 10 
      })
      .then(function (num) {
        console.log(num)
        return num + 100 
      })
      .then(function (num) {
        console.log(num)
      })
      .catch(function (err) {
        console.log(err);
      })
      .finally(function (num) {
      console.log('FINALLY');
    }); 
    出力エラー:

    正常なランタイム出力:

    Reference:
    https://velog.io/@cyranocoding/2019-08-02-1808-%EC%9E%91%EC%84%B1%EB%90%A8-5hjytwqpqj
    https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise
    エリーさんhttps://www.youtube.com/watch?v=JB_yU6Oe2eE
    カバーさんhttps://joshua1988.github.io/web-development/javascript/promise-for-beginners/