I am calling a smart contract function to get some status which is the same as calling an API. And, I need to check if status.fulfilled===true before returning it to front-end. To do this I need to call the API every second to return the result as soon as possible. It usually takes 5-20 seconds for it to be fulfilled.
Here is how i tried to do it:
   async function getStatus(requestId) {
    try {
      await Moralis.enableWeb3({ provider: 'metamask' });
      const options = {
        contractAddress: coinFlipAddress,
        functionName: 'getStatus',
        abi: coinFlipABI,
        params: { requestId },
      };
      var status = await Moralis.executeFunction(options);
      console.log(status);
      if (status.fulfilled) {
        console.log('fulfilled');
        return status;
      } else {
        setTimeout(async () => {
          return await getStatus(requestId);
        }, 1000);
      }
    } catch (err) {
      console.log(err);
      return { error: err };
    }
  }
This keeps calling the getStatus function recursively until status.fulfilled===trueand console.log('fulfilled'); also logs when it is fulfilled, but it doesn't return it to where It is first initialized.
  const handleFlip = async (choice) => {
    setCurrentChoice(null);
    setMetamaskInProgress(true);
    const transaction = await flip(choice, amount);
    setMetamaskInProgress(false);
    setCurrentChoice(choices[choice]);
    setFlipping(true);
    setResult('Spinning');
    const requestId = waitForConfirmation(transaction);
    const result = await getStatus(requestId); //This is the initial call to getStatus()
    console.log('RESULT ' + result);
    if (result) {
      setFlipping(false);
      setSide(result.hasWon ? (choice === '0' ? 'Heads' : 'Tails') : choice === '0' ? 'Tails' : 'Heads');
      setResult(result.hasWon ? 'You have won!' : 'You have lost :(');
    }
  };
What am I doing wrong? Also, could this recursive calls create any problems with memory? If yes, do you have any suggestions to handle this case differently?
 
     
     
    