路由中使用Promise.try的问题
发布于 2 年前 作者 lbchuan 1686 次浏览 来自 问答

写一个接口,刚开始是这样写的

router.post('/uploadImg',  async (ctx)=>{
  let userId = ctx.request.fields.user_id;
  let images = ctx.request.fields.image;
  if(!userId || !images || !images.length){
	  ctx.body = {
		  status: -1,
		  body: {},
		  msg: '参数不全'
	  }
	  return
  }
  try {
	  let imgUrl = await util.getUploadPath(ctx.request.files[0]);
	  ctx.body = {
		  status: 0,
		  body: {
			  img_url: imgUrl
		  },
		  msg: ''
	  }
  }catch (err){
	  ctx.body = {
		  status: -1,
		  body: {},
		  msg: err.message
	  }
  }
})

之后觉得不优雅,就用了Promise.try

Promise.try( async () => {
    let userId = ctx.request.fields.user_id;
    let images = ctx.request.fields.image;
    if(!userId || !images || !images.length){
       throw new Error('参数不全');
    }
    let imgUrl = await util.getUploadPath(ctx.request.files[0]);
    console.log(imgUrl);
    return imgUrl;
}).then( imgUrl => {
    ctx.body = {
        status: 0,
        body: {
            img_url: config.host + imgUrl
        },
        msg: ''
    }
}).catch( err => {
    ctx.body = {
        status: -1,
        body: {},
        msg: err.message
    }
})

在执行到then或catch之前路由方法已经执行完进入下一个中间件,这样不符合我的预期 于是在前面加上了await

router.post('/uploadImg', async (ctx) => {
  await Promise.try( async () => {
	  let userId = ctx.request.fields.user_id;
	  let images = ctx.request.fields.image;
	  if(!userId || !images || !images.length){
		 throw new Error('参数不全');
	  }
	  let imgUrl = await util.getUploadPath(ctx.request.files[0]);
	  console.log(imgUrl);
	  return imgUrl;
  }).then( imgUrl => {
	  ctx.body = {
		  status: 0,
		  body: {
			  img_url: config.host + imgUrl
		  },
		  msg: ''
	  }
  }).catch( err => {
	  ctx.body = {
		  status: -1,
		  body: {},
		  msg: err.message
	  }
  })
})

但总觉得这样不好async和promise混用,大家觉得呢

回到顶部