Tuesday, 30 May 2017

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

this is my code

-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


    }
}

the problem is the first ctx.response.body it can't work,but the other one work well,

-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;

i think pro.js is right, it is not the key of my problem ,so ..who can help me..



via ZZ huang

No comments:

Post a Comment