I am new to nodejs and promises. This is code I wrote by reading some articles but I feel I am not on correct path.
Issue:- In getManager() sometimes neo4j db throws an error while running a query so control ends up in catch block. However, somehow promise will not be resolved after that. So I am not sure if I need to call deferred.reject(returnResults) in catch block.
1) BOT dialog Consumer: calling getPersonInfo()
helper.getPersonInfo(personFullName)
.then(function(results) {
if (results && results.length >= 1) {
//Do something.
} else {
//Do something.
}
})
.catch(function(error) {
//Do something
});
2) how getPersonInfo() looks:
getPersonInfo: function(fullname) {
return Promise.all([
personService.getManager(firstname, fullname, operatorId),
personService.getTeamsMates(firstname, fullname, operatorId)
]);
}
3) How one of the method on promise.all() looks: -
var Q = require('q')
getManager: function(fullname) {
let session = graphDBDriver.session();
let deferred = Q.defer();
let query = function() {
let returnResults = [];
if (fullname) {
let cypherQuery = "Neo4j Query"
session
.run(cypherQuery, { fullname: fullname })
.then(function(result) {
result.records.forEach(function(record) {
if (record && record.length >= 1) {
returnResults.push(record);
}
});
return deferred.resolve(returnResults);
session.close();
})
.catch(function(error) {
session.close();
console.log(" Neo4j error from getManager: " + error);
});
} else {
return deferred.reject(returnResults);
}
}
query();
return deferred.promise;
}
Questions:-
1) Is it good practice to deferred.reject(returnResults) in catch block of getManager()?
2)Any other pattern or code changes I should do as per best practices?.