javascript - 节点:使用猫鼬的 try-catch 中的全局变量
问题描述
try {
globalThis.addResult;
await game
.collection("game")
.findOne({ activity_id }, async (err, result) => {
addResult = result;
});
console.log(`this - ${addResult}`);
return { sucess: true, addResult };
ReferenceError:未定义 addResult
如何设置变量并覆盖 mongoose 查询中的值以返回值?
解决方案
您的代码中的异步和回调混合不好。Mongoose 提供了一个基于 Promise 的 API,可以与 一起使用await
,因此您可以简单地使用它:
const addResult = await game
.collection("game")
.findOne({ activity_id })
.exec();
console.log(addResult);
return { sucess: true, addResult };
推荐阅读
- android - 如果应用程序直接从应用程序托盘中删除,如何取消任何/所有工作经理请求?
- react-native - 为什么不生成设备令牌?
- java - 代码看不到 JTextField 的值,尽管它显示在界面中
- java - 相对布局 getParams 和 setMargin 不起作用
- javascript - animate.css 在 Chrome 最新版本(73 以上版本)中不起作用
- python - Numpy/Pytorch dtype 转换/兼容性
- c# - 什么使控制台应用程序项目
- spring-boot - spring kafka - 无法产生消息和事务回滚不起作用 - org.apache.kafka.common.errors.ProducerFencedException
- javascript - 使用 javascript 中的过滤器转换简单逻辑
- java - kafka 消费者组线程的线程顺序在每次启动时都不同