简体   繁体   English

为什么这个 promise 总是返回未定义而不是值

[英]Why this promise is always returning undefined instead of values

I'm having a problem with promises.我的承诺有问题。 I'm trying to get data from a Mongodb database and returning that data to outside that function.我正在尝试从 Mongodb 数据库中获取数据,并将该数据返回到 function 之外。 The mongodb function is exported and I call that function from another file but I always get undefined. mongodb function 被导出,我从另一个文件中调用 function 但我总是不确定。 How is this managed?这是如何管理的? Thanks in advance!提前致谢!

File with mongo function:带有 mongo function 的文件:

const mongodb = require("mongodb").MongoClient;
const uri = process.env.DB_CONNECT;
const client = new mongodb(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function getPoliticians() {
 const data = async () => await client.connect(async err => {
 return await 
  client.db(process.env.DB).collection(process.env.DB_COLLECTION).find().limit(2).toArray()
});
return await data();
}


module.exports = getPoliticians;

File with mongo function call:使用 mongo function 调用的文件:

const router = require('express').Router();
const mongoF = require('../services/db');

router.get('/get', async (req, res, next) => {
  console.log(await mongoF());
});

module.exports = router;

This console log always prints undefined此控制台日志始终打印undefined

I'm having a problem with promises.我的承诺有问题。 I'm trying to get data from a Mongodb database and returning that data to outside that function.我正在尝试从 Mongodb 数据库中获取数据,并将该数据返回到 function 之外。 The mongodb function is exported and I call that function from another file but I always get undefined. mongodb function 被导出,我从另一个文件中调用 function 但我总是不确定。 How is this managed?这是如何管理的? Thanks in advance!提前致谢!

File with mongo function:带有 mongo function 的文件:

const mongodb = require("mongodb").MongoClient;
const uri = process.env.DB_CONNECT;
const client = new mongodb(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function getPoliticians() {
 const data = async () => await client.connect(async err => {
 return await 
  client.db(process.env.DB).collection(process.env.DB_COLLECTION).find().limit(2).toArray()
});
return await data();
}


module.exports = getPoliticians;

File with mongo function call:使用 mongo function 调用的文件:

const router = require('express').Router();
const mongoF = require('../services/db');

router.get('/get', async (req, res, next) => {
  console.log(await mongoF());
});

module.exports = router;

This console log always prints undefined此控制台日志始终打印undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM