:25}';
console.log(JSON.parse(json));
{name: "xiaoming", age: 25}
异步操作
- 优点:程序性能好,资源利用率高、用户体验好
- 缺点:程序员体验不好
问题:按顺序拉取数据
环境:服务器
我用的是WampServer
data/1.json
{a: 1}
./data/2.json
{b: 12}
./data/3.json
{c: 16}
./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)
}
});
}
});
}
});
{a: 1} {b: 12} {c: 16}
因为这种写法恶心,所以Promise出现了
了解一下Promise,其实jQuery的ajax也是Promise
let p=new Promise(function (resolve, reject){//resolve成功,reject失败
$.ajax({
url: 'data/1.json',
dataType: 'json',
success(data){
resolve(data);
},
error(res){
reject(res);
}
});
});
p.then(function (data){
alert('成功');
console.log(data);
}, function (res){
alert('失败');
console.log(res);
});
怎么用
Promise.all([
$.ajax({url:'data/1.json', dataType: 'json'}),
$.ajax({url:'data/2.json', dataType: 'json'}),
$.ajax({url:'data/3.json', dataType: 'json'})
]).then(([data1,data2,data3])=>{
console.log(data1,data2,data3);
},(res)=>{
alert('错了')//一个接口出错就不渲染
})
{a: 1}a: 1__proto__: Object
{b: 12}b: 12__proto__: Object
{c: 16}c: 16__proto__: Object
但是Promise有个致命的缺点,处理不了逻辑(第一个数据可能决定后面读什么)
因此async/await登场了,专门配合Promise,用同步的方法来写异步。
但是其实编译完还是恶心的嵌套,只不过不需要我们程序员来写,编译就完了
let show = async ()=> {
let data1 = await $.ajax({url: 'data/1.json', dataType: 'json'});//await后面跟的是Promise
let data2 = await $.ajax({url: 'data/2.json', dataType: 'json'});
let data3 = await $.ajax({url: 'data/3.json', dataType: 'json'});
console.log(data1,data2,data3)
}
show();
{a: 1} {b: 12} {c: 16}
处理逻辑
let show = async ()=> {
let data1 = await $.ajax({url: 'data/1.json', dataType: 'json'});
if(data1<10) {
let data2 = await $.ajax({url: 'data/2.json', dataType: 'json'});
console.log(data1,data2)
}else {
let data3 = await $.ajax({url: 'data/3.json', dataType: 'json'});
console.log(data1,data3)
}
}
show();
{a: 1} {c: 16}