03. XMLHttpRequestのPromise化

XMLHttpRequest

 function reqListener () {
   console.log(this.responseText);
 }
 
 var xhr = new XMLHttpRequest();
 xhr.addEventListener("load", reqListener);
 xhr.open("GET", "https://swapi.co/api/people/1");
 xhr.send();
  • ここではXMLHttpRequestでonloadイベントハンドラーにreqListener()を設定して、レスポンスを取得しているが、このレスポンスに対してさらに処理を追加しようとすると、実装が複雑になる
  • Promise化することでこれを整理できる

参考

https://developer.mozilla.org/ja/docs/Web/API/XMLHttpRequest

XMLHttpRequestのPromise化

 function get(url) {
   // Return a new promise.
   return new Promise(function(resolve, reject) {
     // Do the usual XHR stuff
     var req = new XMLHttpRequest();
     req.open('GET', url);
 
     req.onload = function() {
       // This is called even on 404 etc
       // so check the status
       if (req.status == 200) {
         // Resolve the promise with the response text
         resolve(req.response);
       }
       else {
         // Otherwise reject with the status text
         // which will hopefully be a meaningful error
         reject(Error(req.statusText));
       }
     };
 
     // Handle network errors
     req.onerror = function() {
       reject(Error("Network Error"));
     };
 
     // Make the request
     req.send();
   });
 }
 
 get("https://swapi.co/api/people/1").then(function(response) {
   console.log("Success!", response);
 }, function(error) {
   console.error("Failed!", error);
 })
  • Promise化することにより、レスポンスに対して処理を追加するのが比較的簡単になる
  • 以下はレスポンスをJSON.parse()する処理を追加している
 get("https://swapi.co/api/people/1").then(function(response) {
   return JSON.parse(response);
 }, function(error) {
   console.error("Failed!", error);
 })
 .then(function(response) {
  console.log("Yey JSON!", response);
 })

参考

https://developers.google.com/web/fundamentals/primers/promises#xmlhttprequest_%E3%81%AE_promise_%E5%8C%96

参考 fs.readFile()のPromise化

https://stackoverflow.com/questions/41203409/reading-file-with-es6-promises/41203531


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2019-11-05 (火) 07:27:47