使用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'));

//希望每天进步一点点

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,把控制流与函数处理结合在一起显得比较丑陋

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

 

posted @ 2019-08-07 10:05  wiggin  阅读(404)  评论(0编辑  收藏  举报