where()
should return a promise which means you can use then()
and catch()
in the code calling getCount(filter)
of your "service" to access the successful response of values and errors as necessary. According to the documentation, .exec()
can directly be replaced with then()
and catch()
. Try something like the following:
Service:
getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;
// return promise
// using this value directly will not allow you to access queried values
return User.count({ where: whereConditions });
}
Controller/Caller:
this.someService.getCount('someFilterValue')
.then(values = {
console.log(values);
// do something with values like bind to variable/property of the view
})
.catch(error => console.log(error));
Or depending on your structure, you could try something like this to do everything inside of getCount()
:
getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;
// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(values => res.json(values))
.catch(error => res.serverError(error));
}
You can delegate the functionality in the then()
of getCount()
to a separate method to reduce repetition:
getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;
// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(handleResponse)
.catch(error => res.serverError(error));
},
handleResponse: (data) => {
// do something with data
return data.map(e => e.someProperty.toUpperCase());
}
You can chain then()
as necessary to continue transforming values as needed each time returning the transformed values. You can delegate this to methods as long as you continue returning values. This would also allow you take async actions and only acting on them once they are resolved.
getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;
// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(values => values.map(e => e.someProperty.toUpperCase()))
.then(transformedValues => transformedValues.filter(e => e.indexOf(filter) > -1))
.then(filteredValues => res.json(filteredValues))
.catch(error => res.serverError(error));
}
Hopefully that helps!