我是 Node.js 的新手,不确定我是否正确理解 Async/Await。这就是我正在尝试做的事情
我正在将值传递给函数,我希望它像
第 1 步:添加两个值 步骤 2. 根据步骤 1 中的值从数据库中获取文档 步骤 3. 返回步骤 2 中获取的文档。
但是我看到的结果是
第 1 步:添加两个值 步骤 2. 数据库查询运行时返回 undefined 步骤 3. 完成运行查询
如何从中获得所需的输出。
var someFunction = async (a,b)=>{
var k;
try{
k = a+b;
}catch(err){
return(err);
}
var document;
try{
document = await db.collection(somecollection).findOne({_id:k})
}catch(err){
return(err);
}
return(document);
}
someFunction(4,5).then((result)=>{
console.log(result);
});
最佳答案
如果未找到匹配项,
findone
可能会返回未定义
findOne returns undefined on the server
在第一个try...catch
block 中,为什么担心添加两个变量会出现异常?这永远不会导致 javascript 错误。
还要确保您将 _id 正确传递给 findone,Mongo 使用 UUID 来计算 _id
,我认为添加 a + b 无法返回该值
关于javascript - 为什么我的 Async 和 Await 仍然没有完成序列执行的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53311362/