skip to Main Content

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();

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. Perhaps this simple promise using your names will illustrate:

    // fake 
    function FetchSomething(myfoo) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(myfoo);
        }, 2000);
      });
    }
    
    function drawSomething(val) {
      console.log('draw', val);
    }
    
    function drawThing(val) {
      console.log('drawthing', val);
    }
    
    function woops(val) {
      console.log(val);
    }
    
    let handleFulfilled = (val) => {
      drawSomething(val);
      drawThing(val);
      requestAnimationFrame(updater);
    }
    
    let handleRejected = (val) => {
      drawSomething(val);
      woops(val);
      requestAnimationFrame(updater);
    }
    let goodfoo = "good foo";
    
    function updateFun(v) {
      let fetchPromise = FetchSomething(v);
    
      fetchPromise.then(handleFulfilled, handleRejected);
      let t = new Date(Date.now()).getSeconds();
      setTimeout(function() {
        updateFun(goodfoo + t)
      }, 5000);
    }
    updateFun(goodfoo);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search