When my JavaScript file is first loaded, an AJAX request is sent to a database. The trip usually takes about 30ms. On return, the data is stored in a variable. At this point, the variable is either initialized with the data or its initial value is changed. I then need to use the retrieved data.
So it seems I should be able to do something like this:
function async waitForData() {
return new Promise(resolve) => {
resolve(AJAXvariable); // AJAXvariable gets correct value on AJAX return
}
}
waitForData();
or:
const DBdata = async function(){
return await AJAXvariable !== "";
}
In both cases, what’s returned is the current value of AJAXvariable: undefined or “” or false. The await doesn’t happen.
How can I write a promise that checks the value of a variable and doesn’t resolve until that variable changes? Is this even possible?