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

最新文章

  1. ★Kali信息收集~2.Whois :域名信息
  2. .NET/ASP.NET 4.5 Bundle组件(捆绑、缩小静态文件)
  3. js 获取控制台的错误信息
  4. Oracle11G安装之后
  5. 2015 年最棒的 5 个 HTML5 框架
  6. .NET设计模式(10):装饰模式(Decorator Pattern)(转)
  7. C++语法报错收集
  8. 一个js爬虫
  9. (三)----使用HttpClient发送HTTP请求(分别通过GET和POST方法发送数据)
  10. Cts分析框架(4)-添加任务
  11. java宜立方商城项目
  12. Java集合框架之四大接口、常用实现类
  13. UNIX网络编程——网络层:IP
  14. CF1114D 【Flood Fill】
  15. 8.docker的安全性
  16. partial_sum
  17. PHP实现验证码制作
  18. 基于Centos搭建个人 Leanote 云笔记本
  19. 打造一款便携版的Sublime Text
  20. Weekly linux and ConferenceByYear(2002-now)

热门文章

  1. scala调用系统-scala.sys.process使用
  2. 分布式-技术专区-Redis分布式锁实现-第二步
  3. Python第九节 条件和循环
  4. 使用MySQL Workbench查询超时的错误
  5. nuxt项目在windows环境下安装部署
  6. webpack 集成 Typescript && Less
  7. Vuex白话教程第六讲:Vuex的管理员Module(实战篇)
  8. 获取请求url中的参数
  9. Qt【Could not parse stylesheet of object 0x7f7990 】
  10. leetcode-回溯②-难题