【问题标题】:Save into a variable the result from an async function将异步函数的结果保存到变量中
【发布时间】:2021-04-18 12:06:47
【问题描述】:

如何将异步函数的结果保存到变量中,以便在下面使用它? 代码如下所示:

app.post('/reg', function(request, response){
    
    var user = request.body.username;
    var pass = request.body.password;
    var quest = request.body.question;
    var ans = request.body.answer;
    
    

     MongoClient.connect(uri, function(err, db) {
        var dbc = db.db("chat");
        dbc.collection("accounts").find({username: `${user}`}).toArray(async (err, result) => {
            console.log(result.length)
            const a = await result.length;
            return a;
        });

        console.log(a);         <--------- here i got the error: a is not defined

        if(a==1){
            response.send("already_exist");
        }
        else{
            response.send("succes");
            obj={username: user, password: pass, question: quest, answer: ans};
            var dbc = db.db("chat");
            dbc.collection("accounts").insertOne(obj);
        }

        db.close();
        // response.send("yep");
    });
});

我尝试了很多选项,但我找不到任何有用的东西。 我在这里要做的是查找数据库中是否已经存在用户名,如果您有其他想法请告诉我。

【问题讨论】:

  • 您应该在启动应用程序时连接到数据库并共享连接,而不是每次请求都连接。您仍然需要将您的连接从某个模块导出为单例。这样,您的连接将在您运行 npm run whatever 而不是每个请求时开始。

标签: javascript database mongodb asynchronous async-await


【解决方案1】:

变量 a 不在主函数的范围内,请尝试在主/全局级别将其声明在外部。 此外,您正在从函数返回值,只需使用它。

const results = dbc.collection("accounts").find({..

【讨论】:

  • 如果我这样做,其值未定义: const result = dbc.collection("accounts").find({username: ${user}}).toArray(async (err, result) = > { // console.log(result.length) const a = await result.length; return a; });控制台日志(结果);
  • 由于 JS 是非阻塞的,所以结果是不确定的。当您的操作在步骤中发生时,即找到一些东西,然后插入..您需要等到上一步完成。因此,最好的方法是使用 async/await,类似于 stackoverflow.com/questions/47370487/…
猜你喜欢
  • 2023-03-06
  • 2021-06-21
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
相关资源
最近更新 更多