使用promise構建一個向服務器異步數據請求

function getJSON(Url){
  return new Promise((resolve,reject)=>{
        request= new XMLHttpRequest();
        request.open('Get',Url);
        request.onload=function(){
            try{
               if(this.status===200){
                   resolve(JSON.parse(this.response));
               }else{
                   reject(this.status+"" +this.statusText);
               }
            }catch(e){
               reject(e.message);
            }
        }
    request.onerror=function(){
      reject(this.status+""+this.statusText);
    }
    request.send();
}) }

getJSON("data/ninjas.Json").then(ninjas=>{ninjas !== null,'ninjas obtained!'}).catch(e=>console.log('there must smth make an reject'));

//但願天天進步一點點json

promise 與生成器函數的結合promise

function async(generator){
  var iterator =generator();
  function handle(iteratorResult){
     if(iteratorResult.done){return;}
     const iteratorValue=iteratorResult.value;
     if(iteratorValue instanceof Promise){
        iteratorValue.then(res=>handle(iterator.next(res))
                          .catch(err=>iterator.throw(err)); 
     }     
  }
  try{
     handle(iterator.next());
  }catch(e){
     iterator.throw(e);  
  }      
}

//定義好異步函數以後 咱們就能夠調用了異步

async(function*(){
    try{
       const ninjas= yield getJSON('data/ninjas.json');
       const missions= yield getJSON(ninjas[0].missionUrl);
       const missionDescription = yield getJSON(missions[0].detailsUrl);
       //study the missionDetails
    }catch(e){
       //we weren't able to get the mission details
    }
});

 //BTW 自我嘗試,編寫回調形式的getJSON,把控制流與函數處理結合在一塊兒顯得比較醜陋async

function getJSON(url,callback,err){
  request=new XMLHttpRequest();
  request.open('GET',url);
  request.onload=function(){
    try{
       if(this.status===200){
          callback(this.reponse);
       }else{
           err(this.status,this.statusText);  
       }
    }
   request.onerror=function(){
      err(this.status,this.statusText);
   }
   request.send();    
  }      
}
相關文章
相關標籤/搜索