0

I have two files a.js and b.js. The first one runs an async function, which contains a variable that changes everytime something is modified. I want to access the same variable with the modified data in it on another .js file

// a.js

var nodes; // I have defined a global variable
async function createEditor(container) {
    ...
    async function compile() {
        await engine.abort();
        await engine.process(editor.toJSON());
        nodes = engine.process(editor.toJSON());
    }
}

export {nodes};

The second .js file contains: -

// b.js

import {nodes} from './a.js';

console.log(nodes) // Outputs Undefined
dpacman
  • 3,683
  • 2
  • 20
  • 35
  • You're exporting the value of `nodes` before the async function completes (and changes that value) – Quentin Jun 17 '20 at 15:57

1 Answers1

0

Why not inverse the logic?

On file A:

import { log } from './b.js';

var nodes; // I have defined a global variable
async function createEditor(container) {
    ...
    async function compile() {
        await engine.abort();
        await engine.process(editor.toJSON());
        nodes = engine.process(editor.toJSON());

        log(b);
    }
}

export {nodes};

While in file B:

function log(...arguments) {
  console.log(...arguments);
}

export { log };
Mindaugas
  • 1,173
  • 5
  • 15
  • 31
  • 1
    Otherwise, there is this observer/subscriber pattern with getters and setters that was suggested in a similar question: https://stackoverflow.com/a/37403125/2356080 – Mindaugas Jun 17 '20 at 15:56
  • Thank you for the response. I ll check that one out :) – dpacman Jun 17 '20 at 16:04