1

I'm trying to listen for a variable change in node.js
I've tried doing it myself like this:

async function sleep(timeout){
    await new Promise(r => setTimeout(r,timeout));
}
let update=0;
let variable=1;
    
async function latest_value(){
  while(update!=1){await sleep(500);}
    return variable;
}
    
async function set_var(value){
update=1;
variable=value;
}
    
(async ()=>{
   console.log(await latest_value());
})();

set_var(2);

but it's not instantaneous, more of a hack of checking every 0.5secs
so can someone please tell me a way to achieve the desired results efficiently?
Maybe proxy is a way to go?

Note
The above code is just an example of what I need, please do not suggest a ways to bypass the issue

Edit
Also I'm not looking JUST for variable change like this, I need the function to wait on it as well

I've looked into proxy & setters but as far as I could tell they INVOKE a function when value is changed, I need a function that WAITS till the value is changed

This person has the right idea, Look at the 4th comment for reference

  • 2
    A slightly different approach would be to have the watched datum live as a property of an object instead of a local variable, that way you could hook into any mutations to the variable via the `setter` accessor. – zr0gravity7 Jul 02 '21 at 16:33
  • I'm not completely sure what all that means, I'm a bit new. Could you provide appropriate links? –  Jul 02 '21 at 17:20
  • 1
    After a bit of research it seems the Proxy pattern is best. Here's a start: https://stackoverflow.com/questions/1029241/object-watch-for-all-browsers – zr0gravity7 Jul 02 '21 at 17:24
  • Does this answer your question? [Listening for variable changes in JavaScript](https://stackoverflow.com/questions/1759987/listening-for-variable-changes-in-javascript) – code Jul 02 '21 at 19:20

1 Answers1

1

Sounds like you just want to resolve a promise in that set_var call:

let set_var;
const latest_value = new Promise(resolve => {
  set_var = resolve;
});
  
(async ()=>{
  console.log(await latest_value);
})();

set_var(2);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375