Nathan Winspear
Nathan Winspear

Reputation: 119

Await isn't waiting for promise to resolve

Good evening all!

I have been stuck on this issue for a while and I can't seem to solve it through sheer Googling and so I am reaching out to you all.

Context: I am writing a small application that handles all the calendars and basic project information for all the interns at our company because my boss is constantly asking me what they're up to and I wanted to give him something that he could look at, so I decided to solve it with code whilst also learning a new framework in the process(Express).

Right now I have my routes all set up, I have my controllers all set up, and I have my DB cursor all set up. When I make the call to the route I have defined, it runs the getAllUsers() controller function and inside that controller function it makes a call to the database using the getAllUsers() function on the DB cursor, I want the code to wait for the DB cursor to return its result before continuing but it isn't and I can't work out why. The DB cursor code does work because it fetches the data and logs it out fine.

Any help would be greatly appreciated, I have put the three bits of code in question below, let me know if you need me to show more.

p.s ignore the 'here1', 'here2', etc calls, this is how I have been working out what's happening at any point in time.

routes.ts

import express from 'express';
import controllers from './controller.js';

export default (app: express.Application) => {
    // Users
    app.route('/users').get(controllers.getAllUsers)
    app.route('/users').post(controllers.postNewUser)
    app.route('/users').delete(controllers.deleteUser)
    app.route('/user/:emailAddress').get(controllers.getUser)
    app.route('/user/:emailAddress').put(controllers.updateUser)
}

controllers.ts

import express from 'express';
import dbcursor from '../services/dbcursor.js';

// Interfaces
import { Project, User } from '../services/interfaces.js'

const controllers = {

    // Users
    getAllUsers: async (req: express.Request, res: express.Response) => {
        try {
            const dbRes = await dbcursor.getAllUsers();
            console.log('here 3', dbRes)
            res.status(200).json({
                message: 'Users fetched succesfully!',
                dbRes: dbRes
            });
        } catch (err) {
            res.status(400).json({
                message: 'Failed to get users.',
                dbRes: err
            });
            
        }
    },
}

dbcursor.ts

import dotenv from 'dotenv';
import mongodb from 'mongodb' 

dotenv.config();

// Interfaces
import { User, Project } from './interfaces'

// DB Client Creation
const { MongoClient } = mongodb;
const uri = process.env.DB_URI || ''
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

const dbcursor = {
    
    // Users
    getAllUsers: async () => {
        let dbRes;
        try {
            await client.connect(async err => {
                if (err) throw err;
                console.log("here 1", dbRes)
                const collection = client.db("InternManager").collection("Users");
                dbRes = await collection.find().toArray()
                console.log("here 2", dbRes)
                return dbRes;
            });
        } catch(err: any) {
            return err;
        }
    },
}

Upvotes: 1

Views: 1319

Answers (1)

Shadab
Shadab

Reputation: 1347

It's generally not a good idea to mix callbacks and promises. Try not passing a callback to the client.connect method, and you should be able to await the promise as expected

    getAllUsers: async () => {
        let dbRes;
        try {
            await client.connect();
            console.log("here 1", dbRes)
            const collection = client.db("InternManager").collection("Users");
            dbRes = await collection.find().toArray()
            console.log("here 2", dbRes)
            return dbRes;
        } catch(err: any) {
            throw err; // If you're just catching and throwing the error, then it would be okay to just ignore it 
        }
    },

Upvotes: 1

Related Questions