0

Hello I need to call a REST function with an ID, that returns a promise in React.js. This function will at some point contain a certain value in its response when called . Until another service has processed an initial request this value will be null.

This is what I have done so far:

while(myVariable){
    myfunction(myID).then( (response) => {
        if(response['value'] != null
            myVariable = false;
        }
    });
}

The problem with this code is that the while loop is called as fast as possible and thus completely utilises the computer. So I need a function that allows me to poll for a result by an ID until the response of one of the function calls contains a valid response. I have tried the following method but without success, because I don't have a fixed number of runs: Wait promise inside for loop

Thanks in regards.

schande
  • 576
  • 12
  • 27

2 Answers2

2

As you state, the problem is that the while loop runs eagerly, not waiting for each promise to resolve.

One way to solve that is to use recursion. Recursion gives you more control over when exactly you want to 'loop' next:

let getValue = () => {
  myFunction(myID).then(response => {
    if (response['value'] === null) {
      setTimeout(getValue);
    } else {
      // here you know the other service has processed the initial request 
    }
  });
};

First I wrapped the whole thing in a function called getValue. Note that this function is only called again after the promise resolves. (The call to setTimeout is a trick to use recursion without consuming the stack.) If this still runs too quickly, pass an additional parameter of 100 or so to the setTimeout invocation.

Alternatively, you may be able to use async/await similarly to the link you shared. I'm no expert on async/await but it should work the same with while loops as with for loops, judging by this and this.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
2

You can use the async function with await. I also use a delay function to delay each call to the myfunction(). While you get a response, you can break the while loop.

const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));

async function main() {
  const myID = 1;
  let response;
  while (true) {
    response = await myfunction(myID);

    if (response["value"] != null) {
      break;
    }

    await delay(5000);
  }

  //do Something once you get the response here below:
}

main();
ikhvjs
  • 5,316
  • 2
  • 13
  • 36