javascript - node.js - 获取承诺的价值
问题描述
let { errors } = otherValdations(data);
withDB(async (db) => {
return Promise.all([
..code...
]).then(() => {
return {
errors,
isValid: isEmpty(errors),
}
})
}, res).then((result) => {
console.log(result);
})
如何让“结果”变量成为 promise.all 中返回的对象的值?这是 withDB 函数的代码:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('app');
await operations(db);
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error});
}
};
解决方案
您需要进行修改withDB()
,使其返回您想要的值:
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('app');
let result = await operations(db);
client.close();
return result;
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error});
throw error;
}
}
在您的catch()
处理程序中,您还需要做一些事情,以便您的调用代码可以区分您已经发送错误响应的错误路径与您使用该值解析的情况。我不确切知道您希望它如何工作,但我输入了 athrow error
以便它拒绝返回的承诺并且调用者可以看到。
I notice from your error handling that you are assuming all possible errors are causing by an error connecting to the DB. That is not the case here. If operations(db)
rejects, that will also hit your catch
.
推荐阅读
- php - 用php循环遍历xml,无法在同一个数组中获取图像:标题和url
- javascript - 使用 Owl Carousel 2 缩放自定义动画
- python - Scrapy:按顺序抓取网页并在自定义函数中生成抓取的数据
- java - 如何从 Spring 安全身份验证中删除 url 模式?
- javascript - 无法读取未定义的属性“名称”,我需要一些帮助
- blogger - 如何使用按钮创建链接以更改页面并更改新页面的背景颜色
- go - 尝试在 goroutine 中放置 for 循环
- variables - 用 Elisp(输入法)编写一个简单的切换函数
- c++ - 比较运算符与三向运算符的嵌套生成?
- dart - 我可以在地图键中使用对象吗?