首先我们需要了解到底什么是异步操作?promise是怎么解决异步操作的?
- 异步-------多个操作可以一起进行,互不干扰
- 同步-------操作一个一个进行
先来看看ajax是怎么请求多条数据的?
- 我们先新建几个json文件,如:
2. html写入以下代码
$.ajax({
url: 'data/1.json',
dataType: 'json',
success(data1) {
$.ajax({
url: 'data/2.json',
dataType: 'json',
success(data2) {
$.ajax({
url: 'data/3.json',
dataType: 'json',
success(data3) {
console.log(data1, data2, data3);
}
});
}
});
}
});
可以看到ajax如果请求多个文件会比较麻烦
//promise对象是对所有的异步操作进行一个简单的封装
我们简单来模拟一个promise异步操作
Promise.all([ //all等待所有promise操作结束以后,统一来返回一个then
$.ajax({url: 'data/1.json', dataType: 'json'}),
$.ajax({url: 'data/2.json', dataType: 'json'}),
$.ajax({url: 'data/3.json', dataType: 'json'}),
]).then((arr)=>{ //then 不论成功还是失败都是有结果的
let [data1, data2, data3]=arr;
console.log(data1, data2, data3);
}, (res)=>{
alert('错了');
});
单单使用promise处理异步操作是没有任何逻辑在里面,所有我们现在需要使用async和await
async function show(){ //async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数 let data1=await $.ajax({url: 'data/1.json', dataType: 'json'}); //await只能放到async 函数里面,返回一个promise对象 if(data1.a<10){ let data2=await $.ajax({url: 'data/2.json', dataType: 'json'}); alert('a'); }else{ let data3=await $.ajax({url: 'data/3.json', dataType: 'json'}); alert('b'); } } show();
aysnc,await最开心的事情就是以同步操作来进行异步操作了
扫描二维码关注公众号,回复:
5798291 查看本文章