I have a problem don't know why i can't get return data from the function on another file, here what i try
my file.js
const psm = require("../services/psm");
psm.show(12).then((res) => console.log(res));
my service.js
const axios = require("../plugins/axios").default;
const module = "psm";
exports.show = async (payload) => {
await axios
.get(`/${module}/${payload}`)
.then((res) => {
return res.data.data;
})
.catch((err) => {
return Promise.reject(err.response);
})
.finally(() => {});
};
i get undefined return..
CodePudding user response:
Problems in your code:
showfunction doesn't explicitly returns anything; as a result, promise returned by theshowfunction is fulfilled with the value of undefined
Improvements that can be made in your code:
catchandfinallyblocks are not needed;catchblock is unnecessary because rejected promise returned as a result ofcatchblock will need to be handled by the code that calls theshowfunction.You will need the
catchmethod or block in the calling code anyways. So, just remove thecatchblock and allow the calling code to catch and handle the errorshowfunction doesn't needs to beasync. You can just return the result ofaxios.getoraxios.get(...).then(...)
Final version of "show" method:
exports.show = (payload) => {
return axios
.get(`/${module}/${payload}`)
.then((res) => {
return res.data.data;
});
}
You can call this function as:
psm.show(12)
.then(res => console.log(res))
.catch(error => { /* handle the error */ });
Alternate version of show function:
exports.show = (payload) => {
return axios.get(`/${module}/${payload}`);
}
You can call this version of show function as:
psm.show(12)
.then(res => console.log(res.data.data))
.catch(error => { /* handle the error */ });
