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

Activating Unsplash API to initiate download

I am currently following the triggering guidelines found in the Unsplash documentation. The endpoint I am focusing on is: GET /photos/:id/download This is an example response for the photo: { "id": "LBI7cgq3pbM", "width": ...

Struggling with css margins and div image constraints, seeking guidance and tips for resolution

Struggling with creating a dynamic gallery that works smoothly in jsfiddle but encounters multiple issues when integrated into WordPress. The main problem is the excessive stretching of margins between image titles and meta-data, leading to misalignment an ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

"Learn the process of sending a post request using a combination of JQuery, Ajax

I am attempting to send a post request with the following code - var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.data = {}; $scope.reqCalling = function () { ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Preparing data before using Kendo UI upload function is essential

I need to pass a data (specifically a GUID) to the upload method of the kendoUpload, so that a particular MVC Controller action method can receive this data each time the upload occurs. $("#propertyAttachmentUpload").kendoUpload({ async: { ...

What is the best approach to creating multiple dropdowns in ant-design with unique options for each?

It seems like I may be overlooking a simple solution here. Ant-Design dropdowns utilize an array of ItemProp objects to show the options, but this restricts me to having only one list of options. const choices: MenuProps['items'] = [ { label: ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Tips for effectively utilizing the overflow:auto property to maintain focus on the final

I am working on a Todo App and facing an issue where the scrollbars don't focus on the bottom of the page when adding a new element. How can this problem be resolved? https://i.stack.imgur.com/IzyUQ.png ...

Is there a way to refresh the current page in Ionic 3 when the browser is reloaded?

I have encountered a problem in my work with an Ionic 3 App. I am looking for a solution where the browser will refresh the current page instead of redirecting me to the home page. Is this achievable? I attempted to solve it using the following code: thi ...

Upon clicking a button, I aim to retrieve the data from the rows that the user has checked. I am currently unsure of how to iterate through the rows in my mat-table

My goal is to iterate through the column of my mat-table to identify the rows that have been checked, and then store the data of those rows in an array. <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (c ...

Maintain checkbox selection even after the page is refreshed

Having trouble fetching all objects from the favorites array and setting the checkbox to checked. I've attempted using localStorage but the values are not saved after refreshing, despite researching online for solutions. Any assistance would be great ...

Errors in Ionic 6 involving the FormBuilder, FormGroup, Validators, FormControl, and ControlContainer

I am currently working on creating a basic registration form using Ionic 6.12.3 ionic -V, Angular CLI version 11.0.5, and npm version 6.14.11. You can find the repository for this project here: Repo. Below is my implementation for the register.page.ts: // ...

Stop the print dialog box from appearing when using the Ctrl + P shortcut

I'm working on an Angular app and I want to prevent the print dialog from opening when pressing "Ctrl + P". To address this issue, I have implemented the following code: window.onbeforeprint = (event) => { event.stopPropagation(); cons ...

Transforming a string into JSON format for the purpose of implementing JSON Patch

I am encountering an issue while attempting to retrieve a request using postman for a JSON string in order to apply a JSON patch. Unfortunately, I am facing difficulties in converting the string to JSON once the data is posted through a variable. Each time ...

I am looking to modify the visibility of certain select options contingent upon the value within another input field by utilizing ngIf in AngularJS

I am currently utilizing Angularjs 1.x to develop a form with two select fields. Depending on the option selected in the first select, I aim to dynamically show or hide certain options in the second select field. Below is the code snippet for the form: &l ...

Revise a function that locates an object with a corresponding id in an array, modifies a property, and updates a React component's state

Here is a function that takes in a rating value within an object. The ID and Question properties remain unchanged, but the rating value can be updated. This will result in updating a React state value. Is there a method to improve the readability and con ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

"Identifying the exact number of keys in a JSON object using

Is there a key in the JSON data that may or may not exist? How can I determine the total number of occurrences of this key using jQuery? JSON : jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}]; I need assistance with implementing th ...