首页 > 解决方案 > 用于数据库请求的 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();


});

标签: node.jsmongodbpromise

解决方案


您使用回调函数来Promise.all排列。这是正确的使用方法Promise.all

const promises = [
    U4.find({}).count(),
    U4.find({}).count()
];

默认情况下,它返回一个承诺,你必须通过承诺的数组Promise.all


推荐阅读