Recently, I started using promises and came across an issue with a method in my VUE component. Upon debugging, it was evident that the API was returning data and reaching the commented line.
However, upon the function's return, it failed to reach the original caller's .then method. Surprisingly, neither of the alerts I set up seemed to be working either.
I'm questioning whether I am structuring my promise chain incorrectly?
Entrance function
mounted() {
PersonApi.Get(this.personId).then((response) => {
alert('done');
this.person = response;
this.loading = false;
}).catch((error) => {
alert(error);
});
}
Library responsible for making the call
import axios from 'axios'
export default class PersonApi {
private static ResolveApiResponse(response: any): Promise<any> {
return new Promise((resolve) => {
if (response.errors != undefined && response.errors.length > 0) {
Promise.reject(response.errors);
}
Promise.resolve(response.Data); // code is getting to this line
});
}
public static Get(id: number): Promise<any> {
return axios.get('/api/Person/' + id)
.then((response: any) => {
PersonApi.ResolveApiResponse(response.data);
}).catch((error: any) => {
Promise.reject(error);
});
}
}
Updated fixed code snippet
Adjusting to the following
private static ResolveApiResponse(response: any): Promise<any> {
return new Promise((resolve, reject) => {
if (response.errors != undefined && response.errors.length > 0) {
resolve(response.errors);
}
resolve(response.Data);
});
}