Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node:try catch with mongoose中的全局变量_Javascript_Node.js_Mongoose - Fatal编程技术网

Javascript node:try catch with mongoose中的全局变量

Javascript node:try catch with mongoose中的全局变量,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,ReferenceError:未定义addResult 如何设置变量并覆盖mongoose查询中的值以返回值?您可以使用上面的let wait声明一个变量,然后在findone回调中使用它 try { globalThis.addResult; await game .collection("game") .findOne({ activity_id }, async (err, result) => { addResult = re

ReferenceError:未定义addResult


如何设置变量并覆盖mongoose查询中的值以返回值?

您可以使用上面的let wait声明一个变量,然后在findone回调中使用它

try {
  globalThis.addResult;
  await game
    .collection("game")
    .findOne({ activity_id }, async (err, result) => {
      addResult = result;
    });
  console.log(`this - ${addResult}`);
  return { sucess: true, addResult };
更简洁的方法是将wait的返回值指定给
addResult
,然后使用这些值

let addResult;
await game
  .collection("game")
  .findOne({ activity_id }, async (err, result) => {
    addResult = result;
  });
console.log(`this - ${addResult}`);
return { success: true, addResult };

您应该进一步了解javascript中的变量作用域。有很多可用的资源,例如这个

您可以使用上面的let wait声明一个变量,然后在findone回调中使用它

try {
  globalThis.addResult;
  await game
    .collection("game")
    .findOne({ activity_id }, async (err, result) => {
      addResult = result;
    });
  console.log(`this - ${addResult}`);
  return { sucess: true, addResult };
更简洁的方法是将wait的返回值指定给
addResult
,然后使用这些值

let addResult;
await game
  .collection("game")
  .findOne({ activity_id }, async (err, result) => {
    addResult = result;
  });
console.log(`this - ${addResult}`);
return { success: true, addResult };

您应该进一步了解javascript中的变量作用域。有很多可用的资源,例如,这里的代码中混合了异步和回调。Mongoose提供了一个基于promise的API,可与
wait
一起使用,因此您可以简单地使用它:

const addResult=等待游戏
.收藏(“游戏”)
.findOne({activity_id})
.exec();
console.log(addResult);
返回{suces:true,addResult};

您的代码中混合了异步和回调。Mongoose提供了一个基于promise的API,可与
wait
一起使用,因此您可以简单地使用它:

const addResult=等待游戏
.收藏(“游戏”)
.findOne({activity_id})
.exec();
console.log(addResult);
返回{suces:true,addResult};

哦,只有一个小问题。如果有错误怎么办?如果我将其放入
try catch
,那么我就不需要像回调一样进行错误处理了?谢谢buddy@GIHYUNNAM是的,如果您将此代码放入try-catch,则
catch
会收到发生的任何错误。哦,只有一个小问题。如果有错误怎么办?如果我将其放入
try catch
,那么我就不需要像回调一样进行错误处理了?谢谢buddy@GIHYUNNAM是的,如果您将此代码放入try-catch,则
catch
将接收到发生的任何错误。