node.js koa 无法在异步函数中向客户端发送值,但在外部

node.js koa can't sent value to the client in a async function,but outside

这是我的代码

-api.js-

const products=require('../pro');

module.exports ={

    'POST /api/create':async(ctx,next)=>{

        ctx.response.type = 'application/json';

        async function aaa(){
              var data=products();
              return data;
        }
        aaa().then(v=>{
            ctx.response.body=v;//the client show  status 400 
            console.log(v);//here is my json from products(),and it is correct 
        })
        ctx.response.body={a:111};// the client show it correctly


    }
}

问题是第一个ctx.response.body它不能用,但是另一个很好用,

-pro.js-

const model = require('./model/model');

var add=function () {

            return new Promise(resolve =>{

                    model.find({age:18}).lean().exec(function (err, res) {    
                        if(err){
                        }
                        if(res){
                            var result= JSON.stringify(res) ;
                            resolve(result);
                        }

                    });
            })



    }


module.exports = add;

我觉得pro.js是对的,这不是我问题的关键,所以..谁能帮帮我..

我想,这应该遵循 async/await 模式。作为 pro.js returns 的承诺,这非常简单:您的 api.js 可能看起来像这样:

const products=require('../pro');

module.exports ={

    'POST /api/create':async(ctx,next)=>{

        ctx.response.type = 'application/json';

        v = await products()
        ctx.response.body = v;
        // console.log(v);
     }
}

希望有帮助(不是测试)