Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success.

The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted hook, I anticipate the execution of that method. However, upon navigating to the page, neither the promise nor any subsequent actions are carried out. Curiously enough, everything functions as expected when the page is refreshed.

Here is an illustration of my method:

getPosition() {
    return new Promise((resolve, reject) => {
        window.addEventListener("load", () => {
            console.log("window is loaded");
            resolve();
        });
    });
},

And here is how it ties into the mounted hook:

async mounted() {
    console.log("before promise");  // this logs
    await this.getPosition();       // this does not log
    console.log("after promise");   // this does not log
},

Answer №1

getPosition may not always run before load, leading to a potential race condition and unresolved promises. It is important to check if the window has finished loading:

new Promise(resolve => {
    if (document.readyState === 'complete') {
      resolve();
      return;
    }

    window.addEventListener("load", () => resolve());
});

The load event occurs after all images and styles have loaded, causing unnecessary delay in most cases. Waiting for the DOM to be ready is often more practical:

new Promise(resolve => {
    if (document.readyState !== 'loading') {
      resolve();
      return;
    }

    document.addEventListener("DOMContentLoaded", () => resolve());
});

The load and DOMContentLoaded events are expected to trigger only once during the initial page load. Subsequent changes in the DOM or network requests should not rely on them.

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

Firebase will automatically log users out after one hour of inactivity

After conducting thorough research, I have learned that Firebase updates a refresh token every hour because Firebase ID tokens expire after one hour. It is mentioned that the automatic refreshing of tokens by Firebase occurs without any action required fro ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

Utilizing the power of moment.js within an Angular component

My goal is to utilize the moment() function within double curly braces {{}} in order to present a date: {{ moment().date(timeslot.start.value.month) .month(timeslot.start.value.dayOfMonth - 1) .format("MMMM Do") }} Unfortunately, I ...

Is there a way to iterate through objects and add new properties to them?

I am trying to achieve the following object: let newPost = { title: "Post 1", Content: "New content" } with the code below: let newPost = {}; let postData = $(".post-data").each (function(index) { newPost.title = $ ...

Is there a way to transform the searchParams function into an object? Changing from URLSearchParams { 'title' => '1' } to { title : 1 }

Is there a way to convert the searchParams function into an object, transforming from URLSearchParams { 'title' => '1' } to { title : 1 }? I need this conversion to be applied for all values in the URLSearchParams, not just one. Curren ...

How to stop an AJAX request using Chrome developer tools?

Is there a way to cancel an initiated ajax request from Chrome Developer Tools? I want to test if my fallback message displays correctly without changing the code. Setting No throttling to Offline will make all calls fail, but I just need one API to fail f ...

Jquery fails to function properly unless the page is refreshed

On my MVC page, I have implemented a feature where certain text-boxes are shown or hidden based on the value selected in a drop-down menu using jQuery. The functionality works fine when the page is isolated, but when placed under a menu, it encounters a pr ...

Combining Two External Components in VueJS: A Step-by-Step Guide

I am currently utilizing the Form Tags components from the bootstrap-vue framework. My goal is to integrate the vue-simple-suggest component (obtained via npm) with form tags in order to suggest words related to the user's query. Users should be able ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

The data stored in LocalStorage disappears when the page is refreshed

I'm facing an issue with the getItem method in my localStorage within my React Form. I have added an onChange attribute: <div className = 'InputForm' onChange={save_data}> I have found the setItem function to save the data. Here is ...

What is the best way to execute a function in JavaScript and have it return the output as an image

I have created a special function that selects the image source based on a given criterion: function facilityImg(arr, x) { switch (arr[x]) { case 'Yes': return "Images/checked.png"; case 'No': ...

Instructions for sending an array of integers as an argument from JavaScript to Python

I have a JavaScript function that extracts the values of multiple checkboxes and stores them in an array: var selectedValues = $('.item:checked').map(function(){return parseInt($(this).attr('name'));}).get(); My goal is to pass this a ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Experience an enthralling carousel feature powered by the dynamic ContentFlow.js

My website features a cover flow style carousel with 7 images: <!-- ===== FLOW ===== --> <div id="contentFlow" class="ContentFlow"> <!-- should be place before flow so that contained images will be loaded first --> <div class= ...

What could be the reason behind the error message "Java heap space exception in Eclipse" appearing while trying to use JavaScript autocomplete?

Whenever I attempt to utilize a JavaScript template on Eclipse, the program always freezes, displaying an error message stating: "Unhandled event loop exception Java heap space." To troubleshoot this issue, I initiated a top command in Ubuntu for both the ...

What is the best way to provide a static file to an individual user while also sharing its file path

I have integrated jsmodeler (https://github.com/kovacsv/JSModeler) into my website to display 3D models. Currently, users can only select a file using a filepicker or by entering the path in the URL (e.g., http://localhost:3000/ModelView#https://cdn.rawgit ...

encountering a problem with iterating through a JSON array

After making an ajax call and retrieving select options in json format, I implemented the code below to display these new options in place of the existing ones: success: function (data){ var $select = $('#dettaglio'); $select.html(' ...

Update the scrollspy navigation in a div with overflow by toggling the active class

Struggling to implement a navigation menu within a self-scrolling div using html/css/jquery. Looking for the menu items to toggle the active class when in view or at the top of the scrolling div. I'm essentially trying to achieve something like this ...