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