javascript - 在 NodeJS 中返回未定义的异步函数
问题描述
所以,我是新手,试图了解异步函数是如何工作的。使用 Promises 中的“解决,拒绝”来做这件事,效果很好。但是当我尝试使用 async 而不是 new Promise 应用它时,由于某种原因,该函数返回未定义。这是我的代码:)
注意:对不起我的英语,不是流利的演讲者:)
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
})
解决方案
使用时不需要使用callback
函数async/await
试试这个代码:
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
}
推荐阅读
- java - 将 Perl 正则表达式转换为 Java
- python - PySide2 与 qml 作为 ui
- rust - 如何按文件执行“cargo bench”?
- awk - sed:用 NA 替换空列
- deep-learning - 大型数组的快速伪改组
- javascript - Jquery if else 语句不改变变量
- scala - Kafka 消费者每秒消耗不超过 200
- python - Python3:tempfile.mkstemp 文件被自己删除
- php - 如何在 woocommerce 中更改购物车商品数量的设计?
- arrays - 如果 url 属性是数组,则 chrome.tabs.query 找不到匹配项