After going through the "co"
GitHub code, I was able to remove the extra boilerplate code. I made following changes to improve my code:
- Used the
"co"
promise and return it in my async function. This help to remove the extra "Promise" wrapper code. - To resolve the "co" promise, I returned the "Promise" as per fails/success scenario.
- When making call to MongoDB native driver, used
".catch"
to catch the error there itself and apply logic.
Following is my final version which is neater and cleaner using the "co"
module:
#crud.js
crud.js
'use strict';
const db = require("./dbmanager").db;
const co = require("co");
module.exports = {
getAllDocuments: (collectionName)=> {
//return the "co" promise instead of using "Promise" boilerplate code
co(function*() {
let docs = yield db.collection(collectionName).find().toArray().catch(function(err) {
//in case of error, return the custom message and log the error returned by mongodb driver
console.log('Error occurred to get documents', err);
return Promise.reject(new Error(`Error occurred to get documents`)); //return the Promise which will be used by "co"
});
return Promise.resolve(docs); //return the Promise which will be used by "co"
});
}
};
book.js
'use strict';
const dbcrud = require("./crud");
const co = require("co");
module.exports = {
getTransactions: (req, res) => {
//use "co" to make asyn function call without callback
co(function*() {
let transactions = yield dbcrud.getTransactions('transactions');
res.json(transactions);
}).catch((err) => {
console.error(`[ERROR:Controller:API:getTransactions]: error`, err);
res.status(500);
res.json({error: err.message});
});
},
};