javascriptpromisepolling

How to poll a promise in repeating syncroneous code?


Let's say we have some Promise for we knew it resolves at some point. Now I have sync code (ag. no await possible) called repeatedly (eg. onAnimationFrame). How to use the result of the promise there, if it is fullfilled?

Like (JS pseudocode):

let promise=FetchSomething();
let updater = ()=>{
  drawSomething();
  if(promise IS FULLFILLED)  // how to know if fullfilled?
    drawThing(RESULT OF promise); // how to get the result here?
  requestAnimationFrame(updater);
}
updater();

Solution

  • The easiest way is to set a variable yourself:

    let promise = FetchSomething();
    let done = false
    
    /* variable will be set once promise settled */
    promise.then(() => {
        done = true
    })
    
    let updater = () => {
      drawSomething();
    
      if (done) {  
          drawThing(/* RESULT OF promise */); 
      }
    
      requestAnimationFrame(updater);
    }
    
    updater();
    

    You can do the same with the result, i.e.:

    let promise = FetchSomething();
    let done = false
    let result = null
    
    promise.then((value) => {
        done = true
        result = value
    })
    
    let updater = () => {
      drawSomething();
    
      if (done) {  
          drawThing(result); 
      }
    
      requestAnimationFrame(updater);
    }
    
    updater();