node.js - 用于数据库请求的 NodeJS Promise.all
问题描述
如何向数据库发出多个请求,等待所有请求的结果并返回结果?我尝试使用 Promise.all,但我得到的只是控制台中的 [undefined]。
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("DBusers");
var query = {};
var U4 = dbo.collection("users");
const promises = [
U4.find({}).count(function (err, result) { return result; }),
U4.find({}).count(function (err, result) { return result; })
];
Promise.all(promises).then(function (results) {
console.log(results);
}).catch(function (err) {
console.log(err);
});
db.close();
});
解决方案
您使用回调函数来Promise.all
排列。这是正确的使用方法Promise.all
:
const promises = [
U4.find({}).count(),
U4.find({}).count()
];
默认情况下,它返回一个承诺,你必须通过承诺的数组Promise.all
。
推荐阅读
- twilio - 来自 Twilio 工作室的访问号码友好名称
- python - Keras自定义图层调用方法中的批量形状
- php - 空函数在应该返回 true 时返回 false
- forms - CasperJs:如何提交具有 action="" 的表单(没有操作)
- windows - Windows 内核中的 FindFirstFile()
- webdrivermanager-java - 如何抑制 webdriver-manager 日志
- c - 函数在数组中生成随机数
- python - 对于 Django 中的查询集遍历,嵌套 for 循环真的很慢
- java - 从 JSON 中获取所有用户并将其放入 TextView
- java - 哪个 weblogic 类或 jar 包含以下字符串“无法为数据源创建池连接”