2017-05-30 4 views
0

これは私のコードKOAは、非同期機能でクライアントに値を送ったことができないのNode.jsが、外

-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が、他の1つの作業だけでなく、

-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が正しいと思う、それはキーOではありませんf私の問題は、だから私を助けることができます。

答えて

0

私は、これはasync/awaitのパターンに従うべきだと思います。 pro.jsは約束を返すように、これは非常に簡単です:あなたのapi.jsは、このようになります。

のconst製品=が必要です(「../プロ」);

module.exports ={ 

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

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

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

ああ

+0

(testetない)お役に立てば幸いです!!!!できます !!どうもありがとうございます 。この問題は今日私を混乱させました!すごく興奮した –

関連する問題