Home > Mobile >  Export a global variable using asynchronous (async, await) JavaScript
Export a global variable using asynchronous (async, await) JavaScript

Time:08-14

Ok the goal is to be equal a global scope variable to an inner information I need and then export it. But I am not able to do it (I keep getting undefined even though when I console out data, I get the info I want). I have looked at several documentations and other peoples questions NodeJS Async/Await Exporting a Variable , but it still doesn't answer my question. I know I have to use asynchronous JavaScript (async, await) but because I fairly new to JS. NOTE: GETAPRODUCTAPI is a SpringBoot API and updateClick() is called inside another method.

The global variable called dataToExport I want to export and it equals data (then(data)).

export var dataToExport;

const updateClick = () => {
    const editBtns = getQSelectorAll(".edit");
    editBtns.forEach((btn) => {
        btn.addEventListener("click", (e) => {
            const currentClicked = e.currentTarget.dataset.editid;
            const api = GETAPRODUCTAPI   currentClicked;

            fetch(api).then((response) => {
                return response.json();
            }).then((data) => {
                console.log(data); // this works fine
                // TODO
                dataToExport = data
            });
        });
    });
};
console.log(dataToExport); // undefined output

CodePudding user response:

This works but you have to ensure that reading of dataToExport happens after the asynchronous code that actually sets the variable.

That is, through whatever means necessary, you would want to wait to console.log(dataToExport) until after all of the following have occurred:

  1. updateClick is called and the event listener has been bound to the buttons
  2. The button(s) are actually clicked (programmatically or by user interaction)
  3. The fetch(es) are sent out
  4. The response to the fetch(es) are received
  5. The response json is parsed and assigned to dataToExport.

As is you're trying to read dataToExport before any of those steps have occurred and therefore the variable has not been set yet. You can periodically poll to see if the variable has been assigned (e.g. setTimeout or setInterval) or otherwise have an event that triggers a check of this variable.

CodePudding user response:

Based on @arcyqwerty explanation, I was able to figure out a logic. I created two global scopes a variable status and a function changedStatus() . Equalled status to null and then changedStatus() whose job is to check when status changes from null to something else (event that triggers a check of this variable). NOTE: I renamed dataToExport to status

let status = null;
let changedStatus = (value) => {
    status = value;
    if (status != null) {
        console.log(status);
    }
} 

const updateClick = () => {
    const editBtns = getQSelectorAll(".edit");
    editBtns.forEach((btn) => {
        btn.addEventListener("click", (e) => {
            const currentClicked = e.currentTarget.dataset.editid;
            const api = GETAPRODUCTAPI   currentClicked;

            fetch(api).then((response) => {
                return response.json();
            }).then((data) => {
                // TODO
                changedStatus(data);
            });
        });
    });
};

And as far as exporting dataToExport just like @Bergi said it doesn't make sense to export data before user clicks so instead I used localStorage. This example helped for better understanding.

  • Related