I'm working with an Express API using Typescript
I have this method where I'm receiving some data on a callback function
public async getAll(): Promise<GeneralResponse> {
locationsRepo.findAll((error: Error, locations: Location[]) => {
let response: GeneralResponse = {
locations: [],
error: undefined,
};
if (error) response.error = error;
response.locations = locations;
return response;
});
}
My response is a custom object where I store an error (if exists) and an array of a custom object
As you can see in the code above I'm returning the response inside my callback function but I'm getting this error
A function whose declared type is neither 'void' nor 'any' must return a value.
I tried to return my response outside the callback function but the returned value is empty
public async getAll(): Promise<GeneralResponse> {
let response: GeneralResponse = {
locations: [],
error: undefined,
};
locationsRepo.findAll((error: Error, locations: Location[]) => {
if (error) response.error = error;
response.locations = locations;
});
return response;
}
CodePudding user response:
I have encountered the answer in the comments, so I'm publishing the fix I have made to my code
This is the new code on the method I shared in my question
public async getAll(): Promise<GeneralResponse> {
let response: GeneralResponse = {
locations: [],
error: undefined,
};
try {
let result: Location[] = await locationsRepo.findAll();
if (result) response.locations = result;
} catch (error: any) {
response.error = error;
}
return response;
}
But I had to make changes to the other method that was returning data to the main method, I made this changes to use promises instead of callback functions
db.query(queryString, (error, result) => {
if (error) return reject(error);
return resolve(result);
})
Thanks to the people that commented in my question