javascript - 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;
}
},
}
解决方案
混合回调和承诺通常不是一个好主意。尝试不向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
}
},
推荐阅读
- spring-boot - 如何将 testRestTemplate 用于没有请求正文的发布请求
- r - ggplot 标题可以访问 Expss 标签吗?
- python - Python geocoder REQUEST DENIED 即使使用 API 密钥?
- python - 是什么导致 symfit 出现此警告?
- python - 学习游戏时 CNN 模型过度拟合且无法从 OpenCV 序列中正确学习
- android - 我的应用程序仅连接到移动数据中的 Firestore 后端,而不是 wifi
- python - 在 Django 中存储 100k 每日数据库插入的最佳方式是什么?
- java - 数组中最小数的索引位置
- node.js - 在命名空间内找不到名称
- javascript - 通过链接传递状态