#author("2019-11-04T07:31:53+09:00","default:ryuichi","ryuichi")
* 03. XMLHttpRequestのPromise化 [#c74fc22b]

** XMLHttpRequest [#l3371b63]

 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のPromise化 [#ab73be8e]

 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);
 })

トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS