繁体   English   中英

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返回一个promise时,这很简单:您的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);
     }
}

希望有帮助(而不是睾丸)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM