I currently have this isssue where I am calling an API in javascript that returns the status of a submitted job. The job status can be 'QUEUED', 'RUNNING' or 'COMPLETED'. I receive the results of this API call in the form of a promise. I have a function called pollJob that makes an API call and returns a promise that eventually resolves and lets me know whether the job is done or not. My problem is, I have to repeatedly call pollJob until I get a job status that resolves to 'COMPLETED' and then send out some sort of a notification to trigger some sort of action on the front end to occur as a result.
Here is an example of what I have been trying to do so far, but it does not work as Javascript has no notion of a delay function and each timeout will not block but rather fire off, let the code proceed, and then fire off the containing code once the allotted time has passed. I am using setTimeout and multiplying my delay each loop to make the call in staggered instances, basically spreading out each API call because job completion can take up to a minute:
  var res = "";
  var i = 0;
  var delay = 1000;
  while (!api.isJobDone(res) && i < 15) {
    setTimeout(function() {
      api.pollJob()
      .then(function(status) {
        console.log("STATUS IN LOOPUNTILDONE: " + status);  
        (res = status)
        if (api.isJobDone(status)) {
          // let the front end know the job is complete
        }
      });
    }, delay);
    delay *= 3;
    i++;
  }
  return res;
I'm having a lot of trouble thinking about this code in an asynchronous manner and am having a hard time thinking about how to call this promise within a loop until it gives me the desired result and then sending that information out to the front end to let that part of the code know to proceed. Is there a smarter way to design this? Any suggestions or tips are greatly appreciated. Thank you!
 
     
    