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

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

Include an extra hyperlink in the adaptive menu bar

I have successfully created a responsive Navigation bar. Now, I would like to add an "Account" link on the right side of the navigation. My initial thought was to insert a div into a ul element, but I realize that this may not be W3C compliant. <div c ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

Retrieving Blocked Images with Selenium: A Step-by-Step Guide

HTML: <html> <head> <body onload="document.getElementById('a').style.display='block';"> <div id="a" align="center" onclick="document.location.reload();" style="display: block; cursor: pointer;"> <img width="9 ...

Switching Symbols with JQuery

Hello, I am brand new to utilizing javascript and I'm currently experimenting with the toggle function. My goal is to create show/hide functionality while also toggling arrow icons. Specifically, I want a right arrow next to the link "More -->" and ...

Challenges with implementing ng2-auto-complete in Angular2

I successfully integrated the Angular 2 ng2-auto-complete component into my project by following this helpful tutorial. The code is also available on GitHub. The current challenge I am encountering involves the formatting of my data source. It is structur ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Should you construct a fresh element using JavaScript, or opt to reveal a concealed one using CSS?

What are the benefits of using the following approach: var target = document.getElementById( "target" ); var newElement = document.createElement( "div" ); $( target ).after( newElement ); compared to just hiding the newElement div with CSS and showing ...

The asyncio add_signal_handler function is failing to capture the sigint and sigterm signals

I'm currently facing a challenge with debugging an issue in my asyncio project. My goal is to ensure it shuts down smoothly. import asyncio import signal async def clean_loop(signal, loop): print("something") tasks = [t for t ...

Is it possible for me to declare attributes using a function object in a single statement?

Given an object obj, the following two-line statements can be defined: var obj ={} //this is an object obj.isShiny = function () { console.log(this); return "you bet1"; }; These two lines can be combined into a one-line statement ...

Transforming CSV files into JSON format using d3.js

I'm encountering an issue when attempting to convert CSV to JSON. The following is the snippet of code I am using for the conversion: d3.csv("http://localhost:8080/Sample/flight.csv", function(flights) { //alert(flights); ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

How is it possible for this for loop to function properly without the need to pass the incrementing variable

I managed to compile my code and it's working fine, but there's something interesting - the variable that should reference the incrementing value is not included as an argument in the for loop. var _loop2 = function _loop2() { var p = docume ...

Implementing promise-based looping for multiple GET requests in node.js

As a newcomer to promises, I've been searching for the right answer or pattern without much luck. Currently using node.js v4.2.4 and exploring The task seems simple enough... I need to execute multiple asynchronous blocks in a specific order, with on ...

Unable to expand or collapse rows in ng-table

Looking to implement an expand and collapse feature for ng-table, where clicking on a row should expand it to show more detail. However, currently all rows expand on click. Any ideas on how to achieve this? Any assistance would be greatly appreciated, tha ...

"Master the art of implementing a slide toggle effect with jQuery UI using

Looking to implement the jQuery UI slide toggle functionality in plain JavaScript... <center> <button id="button" class="myButton">Read More</button> </center> <div id="myDiv"> <p>Cool Read More Content Here. Lorem Ips ...

Tips for interpreting information from a JSON array that has been stringified, looping through the data, and utilizing it effectively

I'm currently exploring Node JS packages and I need some guidance. Here is an example of the JSON data that I have: [{ "name":"SpiderMan", "description":"Superhero", "head_id":"29", "domain_name":"spiderman.com" }] I am trying to figure out how to ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...