The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function.

I attempted using promises and async await on functions to solve this issue, but without success.

// Button Code

const btn = document.querySelector("button");
        btn.disabled = false;
        btn.onclick = function(e) {

          takeASnap()
            .then(toDataURL)
            .then(async function() {
              Object.keys(await returnData).forEach(function(item) {
                console.log(item); // key
                console.log(typeof item);
                console.log(item);

                console.log(returnData[item]); // value
              });
              console.log(await returnData);
            });

        };
      });

HTML

 <div class="window">
 <video></video>
  <button class="snapshot">take a snapshot</button>
 </div>

toDataUrl

async function toDataURL(blob) {
      let reader = new FileReader();
      let b64;
      reader.readAsDataURL(blob);
      reader.onloadend = function() {
        let base64data = reader.result;
        let count = 0;
        let data;

// ChunkSubstr takes thousand character and put into array that is 
// returned
        b64 = chunkSubstr(base64data, 1000);
        console.log("Hllo");
        webSocket(b64);
      };
    }

webSocket Function

This function assigns the value of return data received from a server.

async function webSocket(b64) {
      const ws = new WebSocket("ws://192.168.1.70:3000");

      ws.onopen = await function() {
        console.log("Connected");

        b64.forEach(element => {
          ws.send(m_imageNr + " " + element);
          // console.log(element);
        });

        m_imageNr++;

        ws.onmessage = function(event) {
          console.log(typeof returnData);

          returnData.push(event.data);
        };
      };

      return await returnData;
    }

Expected behavior is for object iteration to occur on first click, rather than waiting until the second click.

UPDATE: Included requested code.

Answer №1

Improving code structure through refactoring:

const buttonElement = document.querySelector("button");
buttonElement.disabled = false;
async function fetchData() {
   Object.keys(await retrieveData).forEach(function(key) {
      console.log(key); // key
      console.log(typeof key);
      console.log(key);

      console.log(retrieveData[key]); // value
   });
   console.log(await retrieveData);
};

buttonElement.onclick = function(event) {
   takeSnapshot()
      .then(convertToDataURL)
      .then(() => await fetchData());
}

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

Guide to switching from test mode to live mode and enabling live mode in stripe with nodejs

I have encountered an issue with the stripe form I am currently using for payments. When the form is loading, it displays "test mode" in the top right corner. I am unsure how to switch it to live mode and cannot find any option on the stripe dashboard to d ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

Display popup depending on the post's identification number

Currently, I'm in the process of integrating Sanity into my blog. Using the json object returned from a query with useState, I managed to display my posts successfully. However, I am now faced with the challenge of populating a React-Modal with the ap ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

What could be causing my YouTube code to malfunction with certain playlists?

Check out the first jsfiddle playlist here The Alum Songs Playlist is working perfectly, but unfortunately, the same code is not functioning for another playlist ID. View the second jsfiddle playlist here The Medical Animated Playlist is currently not w ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Issue specifically with Android 6 WebView - jQuery 1.9.1 where a RangeError is thrown due to the call stack size being exceeded

An error message "Uncaught RangeError Maximum call stack size exceeded" is causing a web application to fail in the jQuery-1.9.1 extend() function, but strangely it only occurs on Android 6. The application runs smoothly on all other platforms such as Des ...

NodeJs - Issue: Headers cannot be changed once they are sent & TypeError: req.next is undefined

My goal is to retrieve data from a MySQL database by calling methods to insert and read information. The reason I am doing this is because node.js operates asynchronously. Here is my code: exports.list = function(req, res){ var moduleRows; req.getCo ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

What is the process for incorporating a new URL into the routes.js file of a preexisting Node.js project that was developed with locomotive?

module.exports = function routes() { this.root('pages#main'); this.match('/status', 'pages#status'); this.resources('paper'); this.resources('tempform'); this.match('/paper/domain', 'pages#n ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

Difficulty accessing context.params query in Next.js Dynamic Path

I've almost completed setting up a dynamic page in Next.js using getStaticPaths(), but I'm running into an issue with the getStaticProps() function not referencing the URL query correctly to load the relevant information. Here is my code: //Get ...

Error message '[object Error]' is being returned by jQuery ajax

I'm currently facing a challenge with my HTML page that calls an API. Every time I attempt to run it, I encounter an [object Error] message. Below is the code snippet in question: jQuery.support.cors = true; jQuery.ajax({ type: "POST", url: ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

Evolution of ReactJS state over time

When working with React, I wanted to increment a state variable called progressValue by 0.1 every 500 ms until it reaches 100. Here's what I initially tried: const [progressValue, setProgressValue] = React.useState<number>(0) const tick ...

Computed property not properly updating the v-if condition

RESOLVED: I have found a solution that almost solves the issue. By removing <div v-if="isFrameLoaded"> and binding the source data to <video>, the video now loads simultaneously with the request being sent. There is no data in getBLOB ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...