I was trying to use the ES6 Promise
with the "co" module to write the async code without callback. Though actual async call is neat and clean, I still have to add wrapper method to return Promise
object which made it little bulky. Any feedback to improve this code quality will be appreciated.
crud.js
'use strict';
const db = require("./dbmanager").db;
const co = require("co");
module.exports = {
getAllDocuments: (collectionName)=> {
//This line of code returning "Promise" object make code bulky. Now I have two wrapper, one for "Promise" and second for "co".
return new Promise((resolve, reject) => {
co(function*() {
let docs = yield db.collection(collectionName).find().toArray();
resolve(docs);
}).catch((err) => {
reject(err);
});
});
}
};
book.js
'use strict';
const dbcrud = require("./../mongodb/crud");
const co = require("co");
module.exports = {
getTransactions: (callback) => {
co(function*() {
var books = yield dbcrud.getAllDocuments('books');
callback(null, books);
}).catch((err) => {
console.log("Error " + JSON.stringify(err));
callback(err, null);
});
}
};
.find()
normally doesn't return something you can call.toArray()
on. \$\endgroup\$co
return a promise? \$\endgroup\$