我们知道程序有两种运行方式,同步和异步。
promise适合一次读一组数据,方便。下面看看代码
传统的方式:
$.ajax({
url:'1.txt',
dataType:'json',
success(res){
console.log(res);
},
error(){
console.log('出错了')
}
})
$.ajax({
url:'2.txt',
dataType:'json',
success(res){
console.log(res);
},
error(){
console.log('出错了')
}
})
$.ajax({
url:'3.txt',
dataType:'json',
success(res){
console.log(res);
},
error(){
console.log('出错了')
}
})
promsie的方式,通过Promsie.all()
function promiseAjax(url){
return new Promise((resolve,reject)=>{
$.ajax({
url,
dataType:'json',
success(res){
resolve(res)
},
error(err){
reject(err)
}
})
})
}
Promise.all([promiseAjax('1.txt'),promiseAjax('2.txt'),promiseAjax('3.txt')])
.then(res =>{
console.log(res) //res是个数组包含3个异步的结果
},err=>{
console.log('出错:',err)
})
但是对于带有逻辑的请求,promise好像和传统的回调差不了多少。
Promise.all([promiseAjax('1.txt')])
.then(res=>{
if(//逻辑){
Promise.all([promiseAjax('2.txt')])
.then(res=>{
if(//逻辑){}
//...
},err=>{
console.log('出错:',err)
})
}
},err=>{
console.log('出错:',err)
})
这时也就很难维护了,es6中有generator生成器可以解决这个问题
generatorrunner(function * () {
let user = yield $.ajax({url: '1.txt'})
if (user.type == 'VIP') {
let items = yield $.ajax({url: '2.txt'})
} else {
let items = yield $.ajax({url: '3.txt'})
}
})
不过这种要引入runner.js,所以我们还是用自带的async和await来用同步的方式写代码
async function(){
let user = await $.ajax({url: '1.txt'})
if (user.type == 'VIP') {
let items = await $.ajax({url: '2.txt'})
} else {
let items = await $.ajax({url: '3.txt'})
}
}
await只能在async函数中用
这样代码看起来可读性高。嘿嘿。
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- azee.cn 版权所有 赣ICP备2024042794号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务