我的后端代码如下:
exports.getDashboard = (req, res) => {
const dashboard = {};
const query = {};
let start;
let end;
async.parallel([
(callback) => {
const { role } = req.user;
switch (role) {
case 'Admin':
console.log('case admin is working >> >> >> >> >> >> >> >> >> >> ');
start = moment().startOf('day'); // set to 12:00 am today
end = moment().endOf('day'); // set to 23:59 pm today
query.where = {
entryTime: {
$gt: start,
$lt: end,
},
};
break;
case 'Manager':
console.log('case manager is working >> >> >> >> >> >>> >> >> >> >> >> >> >>');
Staff.findOne({
where: {
loginId: req.user.id,
},
}).then((staffData) => {
console.log('staffData', JSON.stringify(staffData));
query.where = {
entryTime: {
$gt: start,
$lt: end,
},
branchId: staffData.branchId,
};
});
break;
default:
console.log('default case');
}
console.log('query >> >> >> >> >> >> >> >> >> >> >> >> >> >> >>', query);
// query is undefined if my case is manager async call.
Visitor.findAndCountAll(query)
.then((data) => {
dashboard.todayentries = data;
callback();
});
},
], (err) => {
if (err) return res.status(500).send(err);
return res.status(200).send(dashboard);
});
};
如果我的案例是经理,则查询不确定。
我已经问过一个异步调用问题,他们建议使用回调,这没关系,但是如何在async.parallel方法中使用嵌套的回调呢?
注意:我不想删除我的async.parallel方法。
答案 0 :(得分:0)
我尝试了另一个回调,工作正常。
这是我尝试过的:
exports.getDashboard = (req, res) => {
const dashboard = {};
const query = {};
let start;
let end;
async.parallel([
(callback) => {
const cb = () => {
Visitor.findAndCountAll(query)
.then((data) => {
dashboard.todayentries = data;
callback();
});
}
const { role } = req.user;
switch (role) {
case 'Admin':
start = moment().startOf('day'); // set to 12:00 am today
end = moment().endOf('day'); // set to 23:59 pm today
query.where = {
entryTime: {
$gt: start,
$lt: end,
},
};
cb();
break;
case 'Manager':
Staff.findOne({
where: {
loginId: req.user.id,
},
}).then((staffData) => {
console.log('staffData', JSON.stringify(staffData));
query.where = {
entryTime: {
$gt: start,
$lt: end,
},
branchId: staffData.branchId,
};
cb(); // my custom callback
});
break;
default:
console.log('default case');
}
},
], (err) => {
if (err) return res.status(500).send(err);
return res.status(200).send(dashboard);
});
};
这是一种好方法吗?