2017-05-30 1 views
0

dies ist mein Codenode.js koa nicht Wert an den Client in einem Asynchron-Funktion gesendet, aber außerhalb

-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 


    } 
} 

das Problem ist die erste ctx.response .body es nicht funktionieren kann, aber die andere Arbeit gut,

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

ich denke pro.js richtig ist, ist es nicht der Schlüssel o f mein Problem, also ..who kann mir helfen ..

Antwort

0

Ich denke, dies sollte die async/await Muster folgen. Als pro.js gibt ein Versprechen zurück, das ist ganz einfach: Ihr api.js könnte dann so aussehen:

const Produkte = erfordern ('../ pro');

module.exports ={ 

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

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

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

Hoffnung, dass (nicht getestet)

+0

oh hilft !!!! Es klappt !! ich danke dir sehr . Dieses Problem hat mich heute verwirrt! sooooooooo aufgeregt –

Verwandte Themen