I've taken over the responsibility of maintaining code written in Vue by my former programmer.
While going through his Vuex module, I came across this piece of code.
import axios from "axios";
import qs from "qs";
import httpi from "../httpInstance"; // a wrapper for axios
const getPromise = (context, url) => {
return new Promise((resolve, reject) => {
httpi.get(url).then(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
};
// similar pattern used for 'put', 'post' etc...
I am puzzled as to why he opted for nested promises like this.
Within ACTIONS
, he utilizes this wrapper to make calls to back-end APIs as shown below.
const actions = {
[ACT_GET_ALL_RULESOURCE]: function (context) {
return getPromise(context, `${APIURLPREFIX}/polapi/api/rulesource`);
},
I'm struggling to understand the rationale behind this approach.
I find it confusing because Axios (httpi
) itself returns a promise. So what is the purpose of nesting promises here?
**edit
In Vue Component methods
, he invokes these actions as follows.
getAllRulesource() {
this.$store.dispatch(`rules/${ACT_GET_ALL_RULESOURCE}`)
.then((res) => {
this.rulesourceList = res.data;
})
.catch((err) => {
this.msg = "Cannot GET rulesource";
})
}