Javascript function always runs last despite being called first

I am facing a situation where I have two functions associated with the Vue object named "form":

form.sizeChartAsImage();
form.setSizeChart();

The code for these functions is as follows:

setSizeChart: function () {
            for (i = 0; i < this.columns.length; i++) {
                this.product.size_chart.push({
                    position_x: 0,
                    position_y: i,
                    value: this.columns[i],
                })
                for (j = 0; j < this.data.length; j++) {
                    for (var key in this.data[j]) {
                        if(key === this.columns[i]) {
                            this.product.size_chart.push({
                                position_x: j+1,
                                position_y: i,
                                value: this.data[j][key],
                            })
                        }
                    }
                }
            }
        }

sizeChartAsImage: function() {
            html2canvas($("#size-chart").get(0)).then(canvas => {
                canvas.toBlob (blob => {
                    var sizechartImg = document.createElement('img');
                    url = URL.createObjectURL(blob);
                    sizechartImg.src = url;
                    this.product.size_chart_image = sizechartImg;
                    debugger;
                }, 'image/png');
            }) 
        }

However, there seems to be an issue where the second function gets executed first (debugger enters first), and then the form is submitted. Subsequently, sizeChartAsImage() runs last, resulting in no effect as the form was submitted with "size_chart_image" being null.

I am attempting to render the following, which successfully generates the image:

<demo-grid
:data="data"
:columns="columns"
id="size-chart">
</demo-grid>

Could this problem be due to it being a Vue component? Are there potential performance issues at play here? Or should I consider using a callback mechanism?

Answer №1

One reason for this behavior is that the function

html2canvas($("#size-chart").get(0))
returns a promise, making it an asynchronous call.

As a result, the sizeChartAsImage function will start running, triggering the execution of

html2canvas($("#size-chart").get(0))
. While waiting for this to complete, the script will proceed to execute the setSizeChart function before returning to process the code within the then(canvas => callback.

To handle this, you can either move the call to setSizeChart to the end of the callback function. Alternatively, if you're using ES2017 or later versions, consider rewriting sizeChartAsImage to use async/await functionality for better code readability.

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

Implementing Jquery Datatables in C# Codebase

I'm struggling to populate my jQuery Datatable with a List. Currently, I am writing the list to a file and accessing it in my view-model. Is this the correct approach? This is the snippet of my code: List<string> list = new List<string> ...

Retrieving Value from Dynamic Content Using jQuery `.keypress()` and `.delegate()`

I have encountered an issue with my code that is unable to retrieve the value of a specific ID on the .keypress function after using .delegate. The ID and other contents are generated dynamically through an AJAX call. $(document).delegate('.edit_ ...

The terminal in VS CODE is not able to detect Stripe

When I attempt to run the command 'stripe listen' in the VS Code terminal, an error is thrown: The term 'stripe' is not recognized as the name of a cmdlet, function, script file, or operable program. Please check the spelling of the ...

Using Threejs to implement mouse events in combination with orbit controls

I've been working on a scene with orbitControls in threejs (r84) and I'm trying to incorporate a mouse event for raycasting. Although the function itself works, I'm having trouble getting both events to work simultaneously. It seems like I c ...

Reactjs button only responds on the second click instead of the first tap

Currently, I am working on a Reactjs/nextjs project and have a video with audio button on my page. There are two things that I want to achieve: 1) I would like the button to have the "bi bi-volume-mute" class by default instead of "bi bi-volume-down". 2) W ...

Issue with Material UI components failing to return an HTMLElement reference

When working with certain libraries that require the ref prop to return an HTMLElement, I have noticed that 99% of MUI components do not fulfill this requirement. What am I missing? How can I obtain a reference to the root element of a component? import R ...

Assign the value in the text box to the PHP session variable

Currently, I am developing a PHP "interactive text game" as a part of my assignment project. My task involves creating a user interface where users input information (such as character names) into text boxes that appear sequentially as they complete the p ...

` ` Despite entering correct values, the HTML form is still displaying validation errors due to JavaScript. ``

My contact form with validations is functioning well, but I am facing an issue where old errors persist even after correcting them and submitting the form again. Below is a snippet of the document containing the JavaScript code: <form id="contactForm" ...

When the parent element's CSS property is set to display: none, ng-repeat fails to function

I have a division with a specific class in the CSS named display: none;. When I click on a button, I switch the class using a toggle class feature called ng-class="vm.showing ? 'zoomIn' : 'zoomOut'". The issue arises when Angular does n ...

Using an onClick event along with jQuery to change the CSS class style of another div

After searching extensively without success, I decided to register and ask my first question here. Hopefully, someone can provide a solution: My goal is to create a set of five buttons (divs) with onClick events that will show five different divs. I' ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Effectively generating observables that extract a designated element from a collection of observables

Within my application, I am utilizing a RxJS subject to broadcast changes within a collection. Each time the collection is updated, the subject emits the new contents as an array format. let collectionSubject = new Rx.BehaviourSubject(); collectionSubjec ...

Exploring the wonders of Ajax with different endpoints for retrieving data

On our server, we have an endpoint set up like this: app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction); When I enter the URL "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00", the server successfully returns data ...

Error in Vuepress: Attempting to read properties that are not defined (specifically 'match')

I encountered an error while attempting to build my vuepress project. I followed this npm quickstart guide: After adding some pages, everything was functioning correctly with: npm run:dev However, when I tried to generate html to docs/src/.vuepress using ...

Exploring scroll functionality with Webdriver.io v4

My code is designed to log into the beta version of mediawiki, navigate to the Preferences page, and attempt to click on a button located at the bottom of the page. In order to achieve this, I am utilizing the scroll() function because using only .click() ...

Encountering obstacles when attempting to save form information to a MongoDB database using Node.js

I've been struggling to save the data entered in my form to my database, but it's not working at all. No errors are showing up and nothing is being logged. Here's the HTML code I'm using: <!DOCTYPE html> <html lang="en"> & ...

Is it possible to repeatedly activate a function using onmousedown just like with onkeydown?

My goal is to have the onmousedown event trigger repeatedly when the left mouse button is held down, instead of just once upon clicking. Currently, it only fires a single time. wHandle.onmousedown = function (event) { console.log('mouse b ...

How can I parse URL paths in jQuery for ASP.NET?

I want to incorporate "~/" and have it resolved on the client side. Here is an example of what I am trying to do: <a href="~/page.aspx">website link</a> <img src="~/page.aspx" /> In my ASP.NET code, I have my base URLs set up like this ...

Retrieve 2 values from a JSON array in a Node.js environment

Can someone assist me in extracting two values from my JSON array? Here is a link to the array: http://pastebin.com/tm5StsZ3 I am looking to retrieve both an ID and a key from these arrays. Any help would be greatly appreciated. I am currently working wit ...