Javascript J.Ka可以膝关节炎;t在异步函数中向客户端发送值,但在外部
这是我的密码 -api.js-Javascript J.Ka可以膝关节炎;t在异步函数中向客户端发送值,但在外部,javascript,node.js,koa,Javascript,Node.js,Koa,这是我的密码 -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
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
返回一个承诺,这非常简单:您的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);
}
}