【问题标题】:Mongoose callback not firing猫鼬回调没有触发
【发布时间】:2015-10-08 04:58:19
【问题描述】:

这是有问题的函数

function matches_password(password)
{
  var modified = false;
  var matched = false;

  User.count({password : password}, function (err, result)
  {
    modified = true;
    console.log('hei');
    if (err)
    {
      //error
    }
    else
    {
      if (result)
      {
        matched = true;
      }
    }
  });

  while (!modified)
  {
    console.log('sleeping');
    sleep.usleep(100000);
  }

  return matched;
}

如您所见,我有一个更新一些变量的回调;执行的主要流程被延迟,直到回调被触发。问题是'hei' 从未出现在控制台中。

删除 while 循环可以解决问题,但我需要它,否则 matched 总是错误的。

发生了什么事,我能做些什么来克服这个挫折?

【问题讨论】:

标签: javascript node.js mongodb asynchronous mongoose


【解决方案1】:

您似乎遇到了异步问题。您可以尝试在调用 User.count(...) 的 while 循环中使用 setTimeout 函数

setTimeout 如何与 Node 一起工作:How does setTimeout work in Node.JS?

【讨论】:

    猜你喜欢
    • 2013-08-05
    • 2013-01-14
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2018-07-12
    • 2017-06-06
    • 2021-03-05
    相关资源
    最近更新 更多