【问题标题】:Run a mongoose query synchronously using async package使用异步包同步运行猫鼬查询
【发布时间】:2023-04-08 08:56:01
【问题描述】:

我想检查用户名是否存在。 我必须同步运行它。

function notExisted(string) {
    var username = '';

    //STEP 1: check if any user is existed with the givven username, and asign a value to username var.
    User.findOne({'username': string}, function (err, result) {
      if (err) {
        req.flash('error', 'An error occured.');
        res.redirect("back");
      } else {
        if (!result === null) {
          username = result.username;
        } else {
          username = null;
        }
      }
    });

    // STEP 2: based on username varibale return false(if founded) or true(if not founded)
    // if any user has founded, the username variable would be the username. Otherwise it would be null.
    if (username === null) {
      return true;
    } else {
      return false;
    }
  }

如您所见,第 1 步和第 2 步应该一个接一个地运行。 您知道如何通过async 库或任何更好的方法同步运行这两个步骤吗? 提前致谢。

【问题讨论】:

  • “我必须同步运行”。为什么?简短的回答:你不能。

标签: node.js mongoose


【解决方案1】:

使用下面的代码,我没有测试过,但这是使用瀑布异步模块的方式:-

let async = require('async');
async.waterfall([
     function(callback) {
          User.findOne({'username': string}, function (err, result) {
               if (err) {
                    callback( true, null);
               } else {
                    if (!result === null) {
                         username = result.username;
                    } else {
                         username = null;
                    }
                    callback( null, username);
               }
          });
     },
     function (username, callback) {
          if (username === null) {
               callback( null, true)
          } else {
               callback( null, false)
          }
     }
], function (err, result) {

     if (err) {
          req.flash('error', 'An error occured.');
          res.redirect("back");
     } else {
          console.log(result);// gives you true / false
     }
})

【讨论】:

  • 或者最好的方法是使用中间件来检查用户名,这样你的主代码的复杂性就会降低。
猜你喜欢
  • 2018-08-09
  • 2021-09-12
  • 2021-12-04
  • 2019-10-12
  • 1970-01-01
  • 2018-08-30
  • 2015-10-23
  • 2018-04-10
  • 1970-01-01
相关资源
最近更新 更多