Omar Ruder
Omar Ruder

Reputation: 116

How do I perform object manipulation on an asynchronous result object?

I was wondering how I can manipulate a JS object from one file, in another, asynchronously. I don't really have a lot of experience with asynchronous code principles.

Situation:
I have a file, app.js, in which I dynamically create 'app panels' based on my HTML.

$("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 be able to override the onActive method in my other file, main.js, but how do I know if this code has finished running? I can't apply .filter() or .find() on app.panels, it will return undefined. I can console.log(app.panels), and it will return the array to my console... but I can't do:

panel = app.panels[0]

this will give me undefined.

I tried to create a function inside of object app, which accepts a callback function that will use app.panels as parameter. This however gives me the same results...

Then I tried to solve it this way:

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


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

this raises the error "TypeError: object is not iterable".

Anyhow, I think my code makes it quite clear that I am not familiar with promises at all, what am I doing wrong?

Upvotes: 0

Views: 49

Answers (1)

Roamer-1888
Roamer-1888

Reputation: 19288

Promisers aren't the solution here. It's all to do with coordination of code loaded from different files.

A typical strategy would be for :

  • all .js files except "main.js" to contain classes/functions, but not execute anything.
  • "main.js" to coordinate everything by creating class instances and calling functions/methods.
  • "main.js" to be loaded last.

Upvotes: 2

Related Questions