skip to Main Content

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


  1. You are using the let statement twice

    When you initialize a variable (let variable = false;) you need to use the let 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.

    Login or Signup to reply.
  2. 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.

    function waitForCondition(name) {
      function waitFor(result) {
        console.log(`result: ${result}`);
        if (result) {
          return Promise.resolve(result);
        }
        return new Promise((resolve) => setTimeout(resolve, 100))
          .then(() => Promise.resolve(window[name]))
          .then((res) => waitFor(res));
      }
      return waitFor();
    }
    
    window.variable = false;
    waitForCondition('variable').then((res) => {
      console.log(res);
    });
    setTimeout(() => window.variable = 123, 500);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search