I want to get a js variable as soon as it’s defined.
I tried this:
function waitForCondition(variable) {
function waitFor(result) {
if (result) {
return result;
}
return new Promise((resolve) => setTimeout(resolve, 100))
.then(() => Promise.resolve([variable]))
.then((res) => waitFor(res));
}
return waitFor();
}
But this will return even on false e.g.:
let variable = false;
waitForCondition('variable').then((res) => { console.log(variable); });
variable = 123;
How to return the variable once it’s set and not false?
2
Answers
You are using the let statement twice
When you initialize a variable (
let variable = false;
) you need to use thelet
keyword.When reassigning a value (the variable has already been initialized), you don’t use the let keyword.
What ever you do to set it could be done in the promise, then you could use a
.then
method to use the set variable.Primitive variables are passed by value in JavaScript, so you will never know when
variable
changes when you simply pass its value in.If you were to use a global value (in this case, a property of
window
), you could just check that each time you polling interval passes. You could then broaden the utility of the function by allowing the user to specify the name of the variable to track.That said, this is all a long, complicated, and less well performing way of avoiding writing code in the place that actually changes the variable.