【问题标题】:Using async functions as conditions使用异步函数作为条件
【发布时间】:2021-11-17 14:16:59
【问题描述】:

假设我想运行条件为异步函数的 if 语句。

const con = require('./con');

if(con.con('email@gmail.com')
  console.log('User exists!')
else {
  console.log('user does not exist?')
}

这是一个函数,它使用了mongoose findOne,它是一个异步任务。

const User = require ('../nodeDB/models/user.js');

const con = function (email) {
     User.findOne( { userEmail: email }, function (err, doc) {
       if(err) {
           console.log(err);
       }
       
       if (doc) {
           return false;
       } else {
           return true;
       }
     });
}

module.exports.con = con;

问题是 if 语句在 con 执行之前被调用,然后不设置条件。

【问题讨论】:

  • 你在使用 async/await 吗?
  • 使用 await,或者在调用函数后将 if 放入 'then' 块中。
  • 尝试添加 async 和 await 但随后它给出了错误 MongooseError: Query was already executed: User.findOne({ userEmail: 'email@gmail.com' })havent 尝试将 if 放在 then 块中,但你的意思是 if。也感谢您的回复。

标签: javascript node.js mongoose


【解决方案1】:

你可以这样做:

const con = userEmail => User.findOne({userEmail}).lean().exec();

(async () => {
    if (await con('email@gmail.com')) {
        console.log('User exists!')
    } else {
        console.log('user does not exist?')
    }
})()
  1. 从您的函数中返回 User.findOne

(可选)2. 添加.lean()(返回简单的JSON,更快)

(可选) 3. 添加 .exec() 使其返回一个真正的 Promise 而不仅仅是一个 thenable

  1. 现在您可以在 async 函数内的任意位置简单地 await con(),就像它是同步的一样。

【讨论】:

    【解决方案2】:

    首先,您的 con() 函数不会返回任何内容。你需要return User.findOne(....)

    您的 if 语句需要尊重异步任务必须先完成这一事实。

    con.con('email@gmail.com')
      .then((exists) => {
         if (exists)
           console.log('User exists!')
         else {
           console.log('user does not exist?')
         }
      })
    

    或者aynsc/await:

    async function checkIfUserExists() {
      if (await con.con('email@gmail.com')
        console.log('User exists!')
      else {
        console.log('user does not exist?')
      }
    }
    
    

    【讨论】:

    • 另外你必须从con()return User.findOne()。目前它没有返回任何东西。
    • @JeremyThille 好点
    【解决方案3】:

    使用await 或将您的逻辑放入then 块中。

    // must be in async declared function
    if (await foo()) {
    }
    else {
    }
    
    // or 
    
    foo().then(res=>{
      if (res) {
      }
      else {
      }
    })
    

    【讨论】:

    • 另外你必须从con()return User.findOne()。目前它没有返回任何东西。
    • @JeremyThille 这就是为什么我只是简单地回答了 op 的问题,而没有提到他们对 con() 的调用。 2个问题:)
    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多