我有一个上传图片的队列
const img_queue=[] as {posturl:string,data:any,cb:Function,err:Function}[]
function img_add(posturl:string,data:any,cb:Function,err:Function) {
img_queue.push({posturl,data,cb,err})
if(img_queue.length==1){
axios.post(posturl,data)
.then(result=>{
img_remove(result,false)
})
.catch(err=>{
img_remove(err,true)
})
}
}
function img_remove(result:any,err:boolean){
const one=img_queue.shift();
(!err)&&one&&one.cb&&one.cb(result);
err&&one&&one.err&& one.err(result);
if(img_queue.length>0){
axios.post(img_queue[0].posturl,img_queue[0].data)
.then(result=>{
img_remove(result,false)
})
.catch(err=>{
img_remove(err,true)
})
}
}
api.post('/uploadImg',(req,res)=>{
//.......
img_add(posturl,data,
(result:any)=>{
res.json(result)
},
(err:any)=>{
res.status(500).json(err)
}
)
})
这样用回调的方式写运行结果是正确的
但当我改用async await形式时:
const img_queue=[]as {posturl:string,data:any,cb:Function,err:Function}[]
async function img_add(posturl:string,data:any,cb:Function,err:Function) {
img_queue.push({posturl,data,cb,err})
if(img_queue.length==1){
try{
const result= await axios.post(posturl,data)
await img_remove(result,false)
}catch(err){
await img_remove(err,true)
}
}
}
async function img_remove(result:any,err:boolean){
const one=img_queue.shift();
(!err)&&one&&one.cb&&one.cb(result);
err&&one&&one.err&&one.err(result);
if(img_queue.length>0){
try{
const result=await axios.post(img_queue[0].posturl,img_queue[0].data)
await img_remove(result,false)
}catch(err){
await img_remove(err,true)
}
}
}
api.post('/uploadImg',async(req,res)=>{
//.....
await img_add(posturl,data,
(result:any)=>{
res.json(result)
},
(err:any)=>{
res.status(500).json(err)
}
)
})
程序的执行似乎不同:
队列中的回调函数似乎只有第一个执行了
请问这是为什么呢?
这里不应该await一个non-promise的函数