I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.
I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.
Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.
items.find({
_id: id
}).then(data => {
uiCtrl.pagination(data, req.query).then((result) => {
res.status(200).send(data);
}).catch((error) => {
console.error(`pagination failed ${error}`);
res.status(500).send(`pagination failed ${error}`);
});
}).catch((error) => {
console.log(`${origin} ${error}`);
res.status(404).send('Not found');
});
Here is the custom async function being called inside the query result above.
const uiCtrl = {};
uiCtrl.pagination = async (data, query) => {
// pagination logic here
return data;
}
module.exports = uiCtrl;
Aucun commentaire:
Enregistrer un commentaire