During the execution of my asynchronous javascript, it interrupts the flow of the other function

How can I ensure that a function executes after another one in Vue.js? I've tried various methods like async/await, callback functions, and .then, but none seem to work seamlessly. Any suggestions for a possible solution?

auth_util.js:

async auth () {
            console.log("authenticating")
            var token = this.getCookie("token")
            var jsonData = {}
            jsonData["token"] = token
            console.log(jsonData)
            var bodyFormData = new FormData();
            bodyFormData.append('data', JSON.stringify(jsonData));
            axios({
                    method: 'post',
                    url: 'backend/index.php?action=checkAuth',
                    data: bodyFormData,
                    headers: {'Content-Type': 'multipart/form-data'}
                    })
                    .then(function (response) {
                      console.log(response);
                      if(response.data.status==="OK"){
                        console.log("ok")
                        return true;
                      }else{
                        console.log("not ok")
                        return false;
                      }
                    })
                    .catch(function (response) {
                        console.log(response);
                        return false;
                    });
           }

Navbar.vue:

created () {
    var result=false
    this.auth().then(this.checkIfLoggedIn(result))
  },
  methods: {
      checkIfLoggedIn (isLoggedIn) {
        console.log("this will be interesting   "+isLoggedIn)
      if(isLoggedIn === true){
        console.log("true")
        document.getElementById("logged_out").style.display="none";
        document.getElementById("logged_in").style.display="block";
      }else{
        console.log("fail");
      }
    }
  }

https://i.sstatic.net/Mao5Y.png

Answer №1

this.authenticate().then(this.verifyLoginStatus(result))

You are facing two issues here.

First: this.verifyLoginStatus(result) executes verifyLoginStatus immediately. To resolve this, you need to pass a function to then.

this.authenticate().then(() => this.verifyLoginStatus(result))

Second: By making that adjustment, you trigger verifyLoginStatus when authenticate resolves.

So when does authenticate resolve? It is declared with the async keyword, so it resolves upon return (unless a promise is returned, in which case it adopts that promise).

What does it return? Since there is no return statement, it defaults to returning undefined once it reaches the end, which is right after calling axios (as you are not awaiting it).

If you were to return the result of axios(...).etc, it would not resolve until that promise is resolved.

(Additional note: Since you are using async, consider refactoring to utilize await and try {} catch() {} instead of .then() and .catch()).

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

Modifying the chart width in Chart.js: A step-by-step guide

After creating a chart using Chart Js, I encountered an issue where the chart did not fit within the specified width. Adjusting the attributes of canvas proved to be ineffective, specifically with regards to the width attribute. Despite changing the value, ...

Get the real code from your production version minimized files using Vue.js

An important functionality we developed using Vue.js was deployed in production but is now only available in minimized form. Unfortunately, the original code for the Vue.js project has been lost, leaving us with only the minimized files (app.js, manifest ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Tips for implementing a controlled RadioGroup in React: Mapping through an array of values to dynamically populate radio buttons

I have a scenario where I am utilizing a pre-defined set of arrays to populate multiple RadioGroups. The component hierarchy in the codesandbox is structured to resemble that of my actual project. Whenever I select a radio button, I receive an error messa ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size. Although I ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

Platform designed to simplify integration of high-definition imagery and scalable vector illustrations on websites

In the ever-evolving world of technology, some clients support advanced features like svg while others do not. With the rise of high resolution devices such as iPhone 4+ and iPad 3rd gen., it has become crucial to deliver graphics that can meet these stand ...

One common query is how to access an HTML element from JavaScript using its ID, particularly when the element belongs to a different HTML document

Following up on the question title: In addition, the HTML document is loaded into the parent element using AJAX in the following way: $.ajax({ url: 'calender.aspx', cache: false, dataType: "html", success: functi ...

Form a hierarchical data structure using a combination of three arrays

Here are three sets of data: let firstData = [ {key: value1}, {key: value2}, {key:value3} ] let secondData = [ {key: value1}, {key: value2}, {key:value3}, {key: value4} ] //same structure, different values let thirdData = [ [1,1,1,1], [1,1,1,1], [1,1,1,1] ...

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

The component name 'Hidden' is not valid for use in JSX

Currently, I'm immersed in a personal project focused on creating a responsive website utilizing Material-UI. In this endeavor, I've leveraged React and kickstarted the project with create-react-app. To enhance the design, I incorporated code fro ...

What is the best way to conceal a website's URL?

Is it possible to hide the actual URL some.otherdomain.com and show only domain.com to visitors of my website? I am looking for a way to mask the URL, perhaps through .htaccess or javascript. Is there any solution available? ...

Guide on Fetching an Image from a Server with Vue Js

I am trying to fetch an image from the server using Vue.js and Laravel. Below is my code: Controller public function index() { $posts = Post::all(); return response()->json(["posts" => $posts]); } Router Route::get('test','Mas ...

Getting the URL path within getStaticPaths in Next.js

Is there a way to retrieve the last number from the current URL pathnames in getStaticPaths? http://localhost:3000/category/food/2 -> 2, http://localhost:3000/category/food/3 -> 3, ... I have attempted: export const getStaticPaths: GetStaticPaths = ...

Issues occur in React when attempting to load an image using TextureLoader in three.js

I have encountered some difficulties while trying to incorporate three.js into a React project. Despite my efforts, I am unable to successfully load texture images. I have set up my own local server, included a callback method for when loading is finished, ...

Step-by-step guide for implementing tooltips using jQuery

I've been attempting to implement a tooltip using jQuery UI. However, when I use var_dump I am not getting any output. Here is the code snippet: <a href="#"><span id='11111_22222'>text_here</span></a> And this is ...

Utilize import and export statements to transfer an HTML tag between two JavaScript files

I have two HTML files linked to two JS files. I want to save an HTML tag from HTML1 with JS1 in a Variable and export it. Then import it in the JS2 file and use it in HTML2 I have tried many ways but nothing seems to work, something as simple as this Exp ...

Why is the Vuetify slider stuck in the center and not budging?

The slider remains static in the center without any movement. https://i.stack.imgur.com/7it9R.png Version Information Vue 3.2.45 Vuetify 3.1.0 Vite 4.0.0 <script> export default { data: () => ({ slider1: 0, slider2: 50, slider3: ...