Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more efficient way to organize it. Therefore, I would greatly appreciate any insights or suggestions on how to improve it.

I feel like my existing setup is convoluted, and I am inclined to explore better alternatives:

login: function() {
    this.toggleLoading();

    this.findUser().then(success => {
        if(success) {
            this.validateSomething().then(success => {
                if(success) {
                    this.auth();
                }
            });
        }
    });
}

The methods findUser and validateSomething are currently structured as follows:

findUser: function() {
    return axios
    .post('/find-user', {
        id: this.id
    })
    .then(response => {
        if(response.data.success) {
            return true;
        } else {
            this.addErrors(response.data.message);
            this.toggleLoading();
            return false;
        }
    })
    .catch(this.catchAll)
},

I prefer not to merge the findUser and validateSomething functions so that I can utilize them independently.

However, my goal is to achieve a structure similar to this instead:

login: function() {

    this.toggleLoading();

    if(!this.findUser()) {
        return false;
    }

    if(this.validateSomething()) {
        this.auth();
    }
}

Can anyone provide recommendations regarding best practices for this specific scenario?

Answer №1

If you prefer promises over async/await, there is a way to clean up your code without nesting them excessively.

Instead of chaining promises like this:

login: function() {
    this.toggleLoading();

    this.findUser().then(success => {
        if(success) {
            this.validateSomething().then(success => {
                if(success) {
                    this.auth();
                }
            });
        }
    });
}

You can streamline it by chaining the promises like so:

login: function() {
  this.toggleLoading();

  this.findUser()
    .then(success => {
      if (success) {
        return this.validateSomething();
      }
      throw new Error('unsuccessful login')
    })
    .then(success => {
      if (success) {
        return this.auth();
      }
      throw new Error('some other reason that it failed')
    })
    .then(success=>{
      return success
    })
    .catch(err=> handle(err))
}

TL;DR;

Promises (without async/await) are perfectly fine, but make sure to chain them properly using .then instead of nesting them as callbacks for cleaner and more efficient code.

Answer №2

Just like @canbax mentioned, remember to utilize the async method along with the keyword await. You can refer to the simple example provided below. The code will halt execution on each await until the promise is resolved.

login: async function() {
    this.toggleLoading();

    const bool = await this.findUser();

    const validated = await this.validateSomething();

    return this.auth();
}

Answer №3

For handling asynchronous tasks in JavaScript, you can leverage the power of async functions, a feature introduced in ES2017. By using the await keyword, you can effectively wait for the result of an async function to be resolved. Be sure to refer to the documentation for more information.

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

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

Isotope: Real-time JSON content extracted from Google Spreadsheet

My goal is to populate an Isotope list using data from a Google Spreadsheet JSON. However, I'm facing issues with the animation and sorting functionality once I add the JSON. Although I have verified that the JSON/JavaScript for loading it works, I am ...

Having difficulty accessing data in a JavaScript file within Odoo 9 platform

I have attempted to extract HTML content from JavaScript declared in my module. However, when I try to retrieve content by class name, all I can access is the header contents and not the kanban view. openerp.my_module = function(instance) { var heade ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

Vuex 3: The State Remains Unknown

software versions: "vue": "2.4.2", "vue-router": "2.7.0", "vuex": "3.0.1" I'm working on simulating a basic login feature with two input fields that will eventually utilize JWT for authenticated logins. However, I'm encountering an issue w ...

Difficulty with linking a CSS property to an HTML element using JavaScript

I'm currently working on building a custom carousel from scratch. Instead of using pre-made code snippets, I decided to challenge myself by creating one using setTimeout in JavaScript. However, I seem to be encountering an issue that I can't quit ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Preventing autoscrolling in Ionic's dual side menu template when additional content is added

Could anyone kindly assist me in figuring out why the autoscrolling of the content is not functioning correctly? Whenever the button on the header is clicked, a new message will be included in the main content. However, once the number of lines exceeds wha ...

Error in jQuery when element is not found

On my website, I use multiple jQuery functions, but not all of them are necessary on every page. These functions are all located in one XXX.js file, such as: jQuery(function() { $(".title").slug({ slug:'slug', hide: false }); }); ...

What is the best way to configure a metered subscription plan on Stripe that invoices annually but bills extra fees for overage on a monthly basis

I'm in the process of setting up a subscription system on stripe that includes a plan with 5000 monthly credits for a flat $299 yearly fee. My goal is to charge customers who exceed their monthly credit limit by the end of each month. For example, if ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

Incorporating Vue 3 with Transition and KeepAlive nested within RouterView

I recently upgraded my application from Vue 2 to Vue 3, but I am experiencing issues with the KeepAlive feature. Despite attempting to navigate back to a previous page included in the KeepAlive, the state does not seem to be cached. Has anyone been able ...

Determine the presence of either one or both values in a JavaScript object

I was looking at an Object like this: {"user": { "name": "Harry Peter", "phoneNumber": "12345", "products": [ { "type": "card", "accountId": "5299367", }, { "type": "Loan", ...

What is the best way to display only the current != wanted lines when using "npm outdated"?

Whenever I input npm outdated, it shows a similar output like this: Package Current Wanted Latest Location columnify 1.1.0 1.1.0 1.2.1 /usr/local/lib > npm > columnify cmd-shim 1.1.2 1.1.2 2.0.0 /usr/local/lib & ...

Choosing Select2: Customizing the context of formatSelection

I've created a simple custom wrapper for Select2, which has been very helpful. However, I am facing an issue with the formatSelection field. When initializing Select2 through my wrapper, it looks like this: this.elem.select2({ allowClear : option ...

What is the best way to position a rectangle on top of a div that has been rendered using

I recently started using a waveform display/play library known as wavesurfer. Within the code snippet below, I have integrated two wavesurfer objects that are displayed and positioned inside div elements of type "container". My goal is to position my own ...

Setting up Karma configuration to specifically exclude nested directories

When unit testing my Angular 2 application using Karma, I encountered an issue with my directory structure: └── src/ ├── index.js ├── index.js.text ├── index.test.js ├── README.txt ├── startuptest.js ...