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

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

Submitting a nested JSON object in an AJAX request

When it comes to passing nested JSON through AJAX, the format of the sample request should be like this: { 'user': { 'email': email, 'password': password } } login(){ var email=document.getElementById(& ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

Learning the process of utilizing Json in Flot to create visually appealing graphs

I'm currently utilizing the Flot Graph Api to showcase bar charts and line charts on my client-side PHP environment. I am attempting to pass Json data to plot the graph as outlined in their examples. This is how I structure the Json data: [{"label": ...

The state variables of React components do not always retain their most recent value

Currently, I am working on implementing the functionality of an event based library called powerbi-client-react. The first step involves retrieving the component using getEmbeddedComponent and storing it in the variable report. Then, I need to utilize the ...

React Error: Unable to iterate over this.state.descriptions

Currently facing an issue while trying to resolve this error https://i.stack.imgur.com/BZ304.png The goal is to generate an automated form using the following function: let descriptionsForm = ( <form> {this.state.descriptions.map((d ...

The VueJS app seems to be experiencing difficulties with rendering the content

Just starting out with VueJS and I have my initial files - index.html and index.js. I want to stick with just these two files and not add any more. Here's the content of index.html: <html lang="en"> <head> <meta charset ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

Eliminate item from array based on certain criteria

In certain scenarios, I must update the filters. Under specific data conditions, I am required to eliminate 1 item from an array. Here is the code snippet: useEffect(() => { let canceled = false; const filters = [ new C ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...

Streamline the testing process to ensure compatibility with jQuery version 2.x

I currently have a substantial JavaScript code base that is all built on jQuery 1.8. I am planning to upgrade to jQuery 2.1 in the near future and I am fully aware that many parts of my code will likely break during this process. Is there any efficient me ...

Adapt appearance according to the length of the text

Currently, I have an array that stores multiple strings based on displayed charts. My objective is to find the longest string within this array. So far, this task has been executed without any issues. The code snippet for this process is as follows: var ...

This particular JavaScript function is only designed to operate on the initial input box in the provided

I have a question regarding echoing rows of $data inside input boxes. I am using a JavaScript function that is supposed to copy the input value to the clipboard when the input box is clicked. However, I am encountering an issue - the function only works ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

The problem of having an undefined state in Vuex arises

https://i.stack.imgur.com/52fBK.png https://i.stack.imgur.com/GcJYH.jpg There is an error occurring: TypeError: Cannot read property 'state' of undefined ...

Do not fetch data again after a re-render

My code is facing an issue where every time I click toggle, the Child component re-renders and triggers another API request. My goal is to fetch the data once and then keep using it even after subsequent re-renders. Check out the CodeSandbox here! functio ...

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

Sort an array using another array as the reference in JavaScript

I have encountered similar questions before, but my current challenge involves partially sorting an array based on values from another array. This is what I aim to achieve: let array = [ { name: "Foo", values: [a, b, c, d] }, { name: " ...

The function of jQuery's .prop('defaultSelected') appears to be unreliable when used in Internet Explorer 9

Below is the code I am currently using: $selects = $('select'); $selects.val( $selects.prop('defaultSelected')); The purpose of this code is to reset the values of all select elements on my webpage. However, I am facing an issue in IE ...