【发布时间】:2020-07-31 03:49:32
【问题描述】:
我有 nodejs 模块来使用 mongodb 驱动程序从 mongodb 数据库中获取数据。回调被传递给给定的函数,该函数返回一个承诺,但不是在 .then() 函数中返回结果,而是将值传递给回调函数。我如何从其他模块或函数调用此函数,因为它没有在 .then() 中返回它?我试图控制 .then() 的结果,但它显示未定义。
const MongoClient = require('mongodb').MongoClient;
const Db = require('../model/db');
Db.findUser = (details, callback) => {
return dbconnection().then(db => {
if (db) {
return db.collection('users').findOne({
email: details.email,
pass: details.password
}).then(data => {
if (data) {
console.log('Found one');
callback(true);
} else {
let err = new Error();
callback(err);
}
})
}
我使用以下函数来调用承诺。我对 Promise 不熟悉。
var getUser = function(callback) {
db.findUser().then(result => {
console.log(result) // undefined
})
}
【问题讨论】:
标签: javascript node.js mongodb promise callback