`Why should you nest promises in Vuex?`

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";
    })
}

Answer №1

The developer before me lacked a solid understanding of promises. It seems that httpi is returning a promise (as seen in the original code which utilizes then), therefore, the function getPromise can and should be restructured as...

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

Alternatively, it could be completely removed. The caller would simply do this instead...

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

If within an async function, the modern way to call it would look like this...

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

"Discover the best way to retrieve data within a Vuex store during the mounted or created lifecycle functions

After storing data in Vuex, I encountered an issue when trying to access my Vuex store after changing routes (components). When inside the mounted function, it shows me an error and fails to return the data. How can I resolve this? I am aware that using a ...

What is the best method for making certain rows uneditable in jqgrid?

Can rows be set as uneditable in jqgrid after the first edit is done? I attempted to add a class called not-editable-row but it did not work. This is how I currently make all rows editable: onSelectRow: function(id){ if(id && id!==lastsel){ g ...

Having trouble building with vue-chartjs (4.1.1) in Nuxt (3.0.0-rc.4)? Looking for a way to implement a basic pie chart in your Nuxt project?

I've been trying to incorporate a reactive pie chart into my Nuxt app using chart.js for quick and efficient results. However, I've hit a roadblock as most resources I find online are for older releases. To help troubleshoot the issue, here is a ...

Instead of the typical Three.js pointer lock first person controls, how about experimenting with orbit

I'm struggling to understand why my controls are causing the camera to orbit around a fixed point instead of behaving like a first-person shooter game. After comparing my code to an example in the three.js documentation, I am aiming to replicate the ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

Modify how the browser typically processes script tags as its default behavior

Most of us are familiar with the functionality of <script src="/something.js"></script>. This loads the specified file onto the page and executes the script contained within. Is there a way to modify how <script> elements are interpreted ...

What is the best way to add pairs of divs to a single div?

Can you help me with this task? <div id="list"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div& ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Leveraging AJAX to populate form fields dynamically depending on user selection

I'm currently facing some challenges in figuring out how to complete this task. Let me provide a brief overview of the scenario and what needs to be achieved. A doctor is capable of adding patients to a database, including details such as their first ...

Error: Unable to access 'map' property of an undefined variable in NextJS while using getStaticPaths

Currently facing an issue with dynamic routing in my Next.js project. I have a dynamic page [id].js and am trying to fetch data from an API. const res = await fetch(`myAPI`); const resData = await res.json(); const paths = resData.data.map((r) =&g ...

Tips for obtaining and storing multiple inputs within the same readline.question prompt in separate variables

Seeking to gather multiple user inputs in a single readline question and assign them to different variables? You're not alone! Ran into this challenge myself while trying to figure out the solution. Code import * as readline from 'node:readline&a ...

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

Struggles with eliminating Mix from a Laravel-Vue hybrid project

My goal is to streamline the process of adopting new features or releases by removing Laravel Mix from my project. I want to avoid using Mix's syntax or plugins and eliminate the need to contain everything within the webpackConfig method. I have succ ...

Introduction to Interactive HTML Pinball Game

As a beginner in the realm of computer science, I've recently embarked on creating a simple pinball game. My approach to maneuvering the flippers involves switching between images that depict the flipper in an upwards and downwards position by utilizi ...

Vue: Component designed exclusively for select pages

In my Symfony project, I am utilizing Vue.js (2) and I currently have a Vue instance with "global" components (specifically an Editor component with some CKEditor libraries) precompiled using the default symfony webpack setup. //app.js import Vue from &apo ...

Encountering issues with accessing 'this' items in the confirmation function of Angular Material's $mdDialog

Attempting to utilize the confirm function within an Angular Material $mdDialog in order to clear an array and then log it to the console is proving problematic. There appears to be an issue with accessing 'this' objects, arrays, expressions, and ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

How come these functions continue to be executed asynchronously even when the Async module is being utilized?

My decision to utilize the Async module aimed at populating a mongodb collection according to a specific order proved to be quite challenging. Despite the fact that the code worked without Async, it failed to insert documents in the desired sequence: func ...