What are the steps involved in manipulating objects within an asynchronous result object?

I'm interested in learning how to manipulate a JS object from one file into another asynchronously, as my experience with asynchronous code principles is limited.

Scenario:
In my app.js file, I dynamically generate 'app panels' based on my HTML structure.

$("div.app-panel[data-panel]").each(function() {
        // create panel objects for all html divs with class app-panel
        var panel = {};
        panel.div = $(this);
        panel.name = $(this).attr("data-panel");
        panel.isActive = ($(this).attr("data-active-panel") == "true" ? true : false);

        panel.onActive = () => {
            // default functionality to execute when activating an app panel
            panel.isActive = true;
            $(panel.div).attr("data-active-panel", true);
        };
        panel.onInactive = () => {
            // default functionality to execute when deactivating an app panel
            panel.isActive = false;
            $(panel.div).attr("data-active-panel", false);
        };

        app.panels.push(panel);
    });

Now, I want to override the onActive method in my other file, main.js. How can I ensure that this code has finished running? Using .filter() or .find() on app.panels returns undefined. While console.log(app.panels) logs the array to the console, trying to access a specific panel like panel = app.panels[0] results in undefined.

I attempted to define a function within the app object which takes a callback function utilizing app.panels as a parameter, yet it yielded the same outcome...

Then, I tried a different approach:

app.getPanels = async () => {
    return new Promise(function(resolve, reject) {
        resolve(app.panels);
    });
};


var getPanels = async (callBack) => {
    const appPanels = await app.getPanels();
    console.log(appPanels);
    callBack(appPanels);
}

However, I encountered the error "TypeError: object is not iterable." It seems clear from my code that my understanding of promises is lacking. What am I overlooking?

Answer №1

Promising to solve the problem is not the answer here. The key lies in effectively coordinating code that is loaded from various files.

An effective approach would involve:

  • Having all .js files, except for "main.js", contain classes/functions without executing anything.
  • "main.js" taking charge of coordinating everything by creating class instances and invoking functions/methods.
  • "main.js" being loaded last in order to execute the coordinated tasks seamlessly.

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

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Create a query string using JavaScript and combine multiple parameters into a single param

I am facing a challenge where I need to construct a query string in JavaScript and nest various parameters within one of the parameters. In PHP, I can achieve this using the http_build_query function. However, when attempting to do the same in JavaScript, ...

Displayed in the xmlhttp.responseText are the tags

Why do tags appear when I input xmlhttp.responseText into my textbox? It displays <!DOCTYPE html><html><body></body></html> along with the desired content. Is there a way to prevent the tags from being displayed? Here is the ...

Oops! Looks like we have encountered an issue with reading the property 'checked' of nothing

Whenever I click the checkbox, an image should be displayed. Unfortunately, I encountered an error: Uncaught TypeError: Cannot read property 'checked' of null at (index):185 at dispatch (VM576 jquery.min.js:3) at i (VM5 ...

What is the best method for ensuring that cheese rises to the top?

Is there a way to increase the value of the variable cheese? I suspect it has something to do with how the variable cheese is defined each time the JavaScript is activated, but I'm not sure how to go about it. Can you offer some guidance on this? & ...

Tips for utilizing jquery.load for fetching a section of an html document or an entire html file

I'm experimenting with jquery's load function to dynamically fetch and display HTML content, rather than using $.ajax(). I enjoy exploring the various features that jQuery offers and want to understand how each one works. Below is the code I am ...

Vue.js $scopedSlots do not function with Vue object

In the process of developing a Vue component that will be released once completed, I am wrapping Clusterize.js (note that the vue-clusterize component is only compatible with v1.x). The goal is to efficiently render a large list of items using Vue, particu ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Discover the size of an image using JavaScript by accessing innerHTML

I'm currently working on a unique AJAX function that retrieves image URLs without using node append for insertion. Instead, I opted to utilize innerHTML, but this has posed challenges in accurately obtaining the file dimensions. My current approach i ...

Leveraging Handlebars for templating in Node.js to incorporate a customized layout

app.js const exphbs = require('express-handlebars'); app.engine('handlebars', exphbs({defaultLayout: 'layout'})); app.set('view engine', 'handlebars'); app.use('/catalog', require('./routes/ ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

I’m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

Using Laravel and vue.js to convert values into an array

I am currently utilizing vue.js within my Laravel project. Within the project, I have three tables: Article Location article_location (pivot table) I am looking to convert location articles into JSON format so that I can pass it to vue. How should I ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Error: selenium web driver java cannot locate tinyMCE

driver.switchTo().frame("tinymce_iframe"); String script="var editor=tinyMCE.get('tinymce_textarea');"; JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript(script); I'm encountering a WebDriverException while try ...

Is there a way to send a non-JSON value to an angular.js http.post function?

Struggling to send two parameters using the HTTP POST method in Angular.js. Here is the code I have implemented: Controller var installerApp = angular.module('installerApp', []); installerApp.controller('InstallerCntlr',function($scop ...

Tips for transferring an array from a php page to a javascript page

In my PHP code, I have an array structured like this: 1) <body onload="addMarkers(<?php print_r($myArray) ?>)"> 2) <body onload="addMarkers(<?php echo json_encode($myArray) ?>)"> Unfortunately, these attempts were unsuccessful. U ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

Unable to retrieve button value with material-ui package

My task requires me to retrieve the value of a button, as it contains an ID essential for further steps. Initially, I used a standard button with Bootstrap styling and everything functioned correctly. <button value={row.vacationRequestID} c ...