Search code examples
javascriptes6-promise

Using JS Promise as an interrupt


I wanted to directly call a function (like interrupt handler) when a certain condition is met. I didn't want to using "polling" for that as it increases time complexity.

count = 1
p = new Promise((resolve, reject)=>{
    
    if(count == 2){
        resolve("hello")
    }
});

p.then((msg)=>{
    console.log(msg)
})

console.log("1 now");
count = 2;
I expected console.log(msg) to run when count=2 but this is not the case. It turned out that the promise is still "pending". What is the reason this happens? And how do I implement my question.


Solution

  • Proxy is one of the solutions for this. But I post another approach for your case.

    You can define a custom class or object, and work with that class. Also you register your custom listener for it, and do whatever.

    This is a sample of my code. Maybe it will give you some ideas for your solution.

    class MyObject {
      constructor(value, func) {
        this._value = value;
        this._listener = func;
      }
    
      get value() {
        return this._value;
      }
    
      set value(newValue) {
        this._listener(newValue);
        this._value = newValue;
      }
    }
    
    function customListener(changedValue) {
      console.log(`New Value Detected: ${changedValue}`);
    }
    
    const count = new MyObject(1, customListener);
    
    count.value = 2;