Guest-01
Guest-01

Reputation: 833

nesting promises in vuex, why?

I'm maintaining vue code from my former programmer.

I've found this code in his vuex module.

import axios from "axios";
import qs from "qs";
import httpi from "../httpInstance";  // this is just a wrapper for axios

const getPromise = (context, url) => {
  return new Promise((resolve, reject) => {
    httpi.get(url).then(
      (response) => {
        resolve(response);
      },
      (error) => {
        reject(error);
      }
    );
  });
};

// same repeated for 'put', 'post' etc...

I'm wondering why he nested promises this way.

In ACTIONS, he uses this wrapper to call back-end API like below.

const actions = {
  [ACT_GET_ALL_RULESOURCE]: function (context) {
    return getPromise(context, `${APIURLPREFIX}/polapi/api/rulesource`);
  },

What was he trying to achieve by this?

I'm so confused since axios(httpi) itself is already a promise. what is the point here?

**edit

In Vue Component methods's, he uses this actions like below.

getAllRulesource() {
  this.$store.dispatch(`rules/${ACT_GET_ALL_RULESOURCE}`)
    .then((res) => {
      this.rulesourceList = res.data;
    })
    .catch((err) => {
      this.msg = "Cannot GET rulesource";
    })
}

Upvotes: 1

Views: 116

Answers (1)

danh
danh

Reputation: 62676

The prior developer didn't understand promises well enough. Since it appears that httpi returns a promise (the OP code calls then on it) the function getPromise can and should be rewritten as...

const getPromise = (context, url) => {
  return httpi.get(url);
};

Or removed altogether. The would-have-been caller can just say...

httpi.get('http...').then(response => {
  console.log(response);
}).catch(error => {
  console.log(error);
})

Inside a function declared as async, the more modern caller syntax is...

try {
  const response = await httpi.get('http...');
  console.log(response);
} catch(error) {
  console.log(error);
}

Upvotes: 1

Related Questions