[英]Async function returning undefined in NodeJS
So, I'm new trying to understand how async functions work.所以,我是新手,试图了解异步函数是如何工作的。 Doing it with "Resolve, Reject" from Promises, works fine.
使用 Promises 中的“解决,拒绝”来做这件事,效果很好。 But when I try to apply it with async instead of new Promise, for some reason, the function returns undefined.
但是当我尝试使用异步而不是新的 Promise 应用它时,由于某种原因,function 返回未定义。 Here is my code:)
这是我的代码:)
note: Sorry for my english, not fluent speaker:)注意:对不起我的英语,不是流利的演讲者:)
category = body.category
obtenerCategoria = async(category) => {
Categoria.findOne({ descripcion: category })
.exec((err, categoriaDB) => {
if (err) {
throw new Error(err)
}
if (!categoriaDB) {
return res.status(400).json({
ok: false,
msg: 'Categoria no encontrada'
})
}
console.log(categoriaDB); // Works fine here
return categoriaDB
})
}
crearClase = async() => {
categoria = await obtenerCategoria(category);
console.log(categoria); //getting nothing here
}
crearClase()
.then()
.catch(e => {
return e
})
You don't need to use callback
function when you use async/await
使用
async/await
时不需要使用callback
function
Try this code:试试这个代码:
obtenerCategoria = async(category) => {
const categoriaDB = await Categoria.findOne({ descripcion: category });
if (!categoriaDB) {
return res.status(400).json({
ok: false,
msg: 'Categoria no encontrada'
})
}
console.log(categoriaDB); // Works fine here
return categoriaDB
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.