我正在尝试使用 Mongoose 和 ExpressJS 在 MongoDB 中运行两个异步查询。
exports.get_options_data = function (req, res) {
var rooms = [];
var areas = [];
async.parallel({
rooms : AddProperty.distinct("roomQty", function (err, data) {
if (err)
res.send({ code: '500', message: err });
rooms = data;
}),
areas: AddProperty.distinct("area", function (err, data) {
if (err)
res.send({ code: '500', message: err });
areas = data;
})
}, function(err, data){
res.send({ code: '200', rooms: rooms, areas : areas });
})
}
为此,我使用异步并行。我已经使用 npm i async
安装了 async。
我想要的是,执行这两个查询并将查询响应作为组合 JSON 一起发送。
但是,当我执行此操作时出现错误:
TypeError: wrapAsync(...) is not a function
另外,有没有更好的方法来做同样的事情?
最佳答案
异步。 parallel
接受函数数组而不是对象。
Node 现在支持 Promise,因此您只需使用 Promise.all
作为替代品。您可以使用 util.promisify
将 AddProperty.distinct
转换为基于 Promise 的函数。
const util = require('util');
const addProperty = util.promisify(AddProperty.distinct);
Promise.all([
addProperty('roomQty'),
addProperty('area')
]).then((data){
res.send({ code: '200', rooms: data[0], areas : data[1] });
}).catch(error => {
res.send({ code: '500', message: error });
});
关于node.js - wrapAsync(...) 不是 MongoDB 和 Mongoose 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55350965/