I have a promise which contains another API caller promise containing resolver. Now when I want to use the .then for parent promise, I am not able to do it, error says Cannot read property 'then' of undefined
, below is my sample code
const getData = () => dispatch => new Promise((resolve) => {
return apiService
.getByParameter(abc)
.then((data) => {
dispatch(update({
name: data.name
}));
resolve();
})
.catch(() => {
});
});
Now whenever I try to do
this.getData().then({
<--something-->
});
It throws ne error as Cannot read property 'then' of undefined
the method getByParamter comes from a Class, as
getByParameter(...params) {
const endpoint = `${this.getEndpoint.call(this, ...params)}`;
const timeInitiated = performance.now();
return request(() => axios.get(endpoint, extraHeaders), timeInitiated,
endpoint, ACTIONS.ACTION_GET);
}
const request = (rest, timeInitiated, endpoint, action) =>
new Promise((resolve, reject) => {
rest().then(({ data }) => {
const timeResolved = performance.now();
const timeCalculated = millisToMinutesAndSeconds(timeResolved - timeInitiated);
if (endpoint !== LOGS_ENDPOINT && timeCalculated > MAX_EXECUTION_TIME) {
apiLogger.warn(`The endpoint ${endpoint} took ${timeCalculated} seconds for ${action}`);
}
resolve(data);
})
.catch((response) => {
if (!isCancel(response)) {
reject(response);
} else {
apiLogger.debug('Request cancelled');
}
});
});
Please suggest what should be the solution to achieve what I need.
Your arrow function immediately, and unconditionally returns another function, not a promise!
const getData = () => (dispatch => new Promise(...))
getData()
is a function, so .then
does not exist on it.
Try it yourself
console.assert(typeof getData() !== "function", "`.then` doesn't exist on a function");
Honestly, this code ought to remove the dispatch callback and let the callee use a .then
handler, that's what promises are for.
const getData = async () => {
const data = await apiService.getByParameter(abc);
return update(data);
});