首页 > 解决方案 > Await 不是在等待 promise 解决

问题描述

大家晚上好!

我已经在这个问题上停留了一段时间,我似乎无法通过纯粹的谷歌搜索来解决它,所以我正在与大家联系。

背景: 我正在编写一个小应用程序来处理我们公司所有实习生的所有日历和基本项目信息,因为我的老板经常问我他们在做什么,我想给他一些他可以看的东西,所以我决定用代码解决它,同时也在这个过程中学习一个新的框架(Express)。

现在我的路线都设置好了,我的控制器都设置好了,我的数据库游标也设置好了。当我调用我定义的路由时,它运行 getAllUsers() 控制器函数,并在该控制器函数中使用 DB 游标上的 getAllUsers() 函数调用数据库,我希望代码等待DB 游标在继续之前返回其结果,但事实并非如此,我不知道为什么。DB 游标代码确实有效,因为它可以获取数据并将其很好地记录下来。

任何帮助将不胜感激,我已将这三位代码放在下面,如果您需要我展示更多内容,请告诉我。

ps 忽略“here1”、“here2”等调用,这就是我一直在计算任何时间点发生的事情的方式。

路线.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)
}

控制器.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;
        }
    },
}

标签: javascriptnode.jstypescriptexpressasync-await

解决方案


混合回调和承诺通常不是一个好主意。尝试不向client.connect方法传递回调,您应该能够await按预期兑现承诺

    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 
        }
    },

推荐阅读