大家看到回调地狱可能就有点蒙了!这是个什么鬼?
哈哈哈,虽然你可能没有听过 但只要你处理过复杂的管理系统,那你很有可能就亲手写出过回调地狱哦
简单说就是异步操作 我们在调用一个axios时就会有一个请求成功的方法。
比如 你需要向后端请求当前目录ID 在通过当前的目录ID去请求电表ID,在用电表ID去请求用量
那我向你的代码很有可能是这样的
api.getCatalogue({id:id}).then((res)=>{
if(res && res.code==200){
api.getWattHourMeter({id:res.data.id}).then((res)=>{
if(res && res.code==200){
api.getConsumption({id:res.data.id}).then((res)=>{
if(res && res.code==200){
//逻辑操作
}
})
}
})
}
})
相信大家一看就会简单这样写感觉很不舒服吧?在异步操作的成功回调中再调用异步操作,这样一层包一层就像是18层地狱一样,因此这种现象被称作回调地狱
其实我还是封装了axios再利用Promise作了箭头函数的简写,相信如果你直接写在axios原型里会更加难看
因为ES6的诞生 这个显然已经不是什么问题了
我们可以用
async await 解决这个问题
比如我们在vue的created生命周期中编写这个方法
async created () {
const Catalogue = await api['getCatalogue']({id:id});
const WattHourMeter = await api['getWattHourMeter']({id:Catalogue.id})
const Consumption = await api['getConsumption']({id:HourMeter.id})
//逻辑操作
}
还有就是对Promise更深层次的使用也可以解决这种问题
const getCatalogue = function(id){
return promise = new Promise((resolve,reject) =>{
api.getCatalogue({id:id})
})
}
const getWattHourMeter= function(id){
return promise = new Promise((resolve,reject) =>{
api.getWattHourMeter({id:id})
})
}
const getConsumption = function(id){
return promise = new Promise((resolve,reject) =>{
api.getConsumption({id:id})
})
}
getCatalogue(id).then((res)=>{
return getWattHourMeter(res.data.id)
}).then((res)=>{
return getConsumption(res.data.id)
}).then((res)=>{
//数据操作
})