简体   繁体   中英

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. The mongodb function is exported and I call that function from another file but I always get undefined. How is this managed? Thanks in advance!

File with 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:

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

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. The mongodb function is exported and I call that function from another file but I always get undefined. How is this managed? Thanks in advance!

File with 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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