I have this function
/* GET main page */
router.get('/', (req, res, next) => {
Account.find({accType: 'Employer'}, (err, col) => {
if (err) {
console.log(err);
} else {
Banner.findOne((err, banner) => {
if (err) {
console.log(err);
} else {
// Determine whether there is at least one awaiting account.
Account.findOne({accType: 'Awaiting'}, (err, doc) => {
if (err) {
console.log(err);
} else {
if (doc != null) {
var awaiting = true;
}
console.log(doc);
res.render('admin/', {
title: 'Admin pannel',
user: req.user,
employers: col,
areAwaiting: awaiting,
banner: banner,
)
}
}
);
}
});
}
});
});
I tried using the async module like this:
async.parallel(calls, (err, col) => {
if (err)
console.log(err);
else {
console.log(col);
res.render('admin/', {
title: 'Admin pannel',
user: req.user,
employers: col[0],
banner: col[1],
areAwaiting: col[2],
})
}
});
Now. The error I'm getting is wrapAsync(...) is not a function. I tried putting my functions in anonymous functions like this:
() => {
Account.find({accType: 'Employer'}, (err, col) => {
if (err)
console.log(err);
else return col;
})
}
but then the code just freezes. I also tried this:
(col) => {
Banner.findOne((err, doc) => {
if (err)
console.log(err);
else return doc;
});
return col
},
but with the same effect. Any idea what I'm doing wrong? The callback hell version works, but is just ugly and not maintainable.
Answer by Dave Meehan. Had to edit it slightly to make it work.
router.get('/', (req, res) => {
return Promise.all([
Account.find(),
Banner.findOne(),
Account.findOne({accType: 'Awaiting'}),
]).then(([employers, banner, awaiting]) => { // Right here
if (awaiting != null)
var areAwaiting = true;
res.render('admin/', {
title: 'Admin pannel',
user: req.user,
employers: employers,
areAwaiting: areAwaiting,
banner: banner,
});
}).catch(e => {
console.error(e)
});
});
I had to close the array in then
into ()