猫鼬在模型上的findOne是否返回承诺

猫鼬在模型上的findOne是否返回承诺

本文介绍了猫鼬在模型上的findOne是否返回承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Node模块,该模块导出一个函数来进行数据库查询.问题在于该函数在数据库查询完成之前返回.

I have a simple Node module that exports a function that makes a database query. The problem is that this function returns before the database query completes.

"use strict";

var mongoose = require('mongoose'),
    Model    = require('./entities/user/model'),
    _        = require('underscore');

let dao = new Model(mongoose);

module.exports.isAdmin = function(user_id) {
  var params = {'roles': 'admin'};

  dao.findOne(params, function(err, user) {
    if (err) {
      logger.error(err);
      return false;
    }
    if (_.indexOf(user.roles, 'admin') != -1) {
      logger.info("admin user: " + user._id);
      if (user._id == user_id) return true;
    }
    return false;
  });
};

isAdmin函数搜索用户集合,以查明user_id是否属于管理员用户.

isAdmin function searches the users collection in order to find out if user_id belongs to admin user.

问题在于isAdmin函数不等待findOne查询的响应.

The problem is that isAdmin function doesn't wait for the response of findOne query.

如何强制isAdmin函数仅在查询返回结果时返回?

How could I force the isAdmin function to return only when query returns results ?

推荐答案

由于findOne async 函数,从中返回的一种方法是通过callback函数

Because findOne is async function, one way to return from it is through callback function

module.exports.isAdmin = function(user_id, callback) {
  var params = {'roles': 'admin'};

  dao.findOne(params, function(err, user) {
    if (err) {
      logger.error(err);
      callback && callback(false);
    }
    if (_.indexOf(user.roles, 'admin') != -1) {
      logger.info("admin user: " + user._id);
      if (user._id == user_id)
          callback && callback(true);
    }
    callback && callback(true);
  });
};

isAdmin(userId, function(v) {
    console.log(v);
})

另一种方法是在 findOne 中获得承诺,给您一个完整的承诺.即使使用Promise,为了满足您的要求,也可以通过回调函数返回结果.

Another way is to get Promise in findOne, as this doc said, .exec() gives you a fully-fledged promise. Even with Promise, to meet you requirement, the result could be returned through callback function.

module.exports.isAdmin = function(user_id, callback) {
  var params = {'roles': 'admin'};

  var queryPromise = dao.findOne(params).exec();
  queryPromise.then(function(user) {
      if (_.indexOf(user.roles, 'admin') != -1) {
        logger.info("admin user: " + user._id);
        if (user._id == user_id)
          callback && callback(true);
      }
    }, function(err) {
      callback && callback(false);
  });
};

这篇关于猫鼬在模型上的findOne是否返回承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:07