0

Ahh I really didn't want to ask, but my brain is really frying about this now.

I have a function that polls information from database API:

function fetchDatabase() {
let fetchResult = database.fetch.local(something, apiHost("api.database.com"));
return fetchResult
}

The value of fetchResult that this function gets, needs to be updated every second. So I am putting 1 second interval on the whole function:

setInterval(fetchDatabase, 1000)

Now I need to be able to access this data as a variable >>> !!! OUTSIDE !!! <<< of the function so I write:

let outsideResult = await fetchDatabase();

I then verify my code with this:

console.log(outsideResult)

I am successfully getting output of "fetchResult" every second, but the problem is, that this value does NOT update as the database API from which I'm polling the "fetchResult" gets updated.

So I am getting the same values all the time and not updated ones.

Please, how can get updated result of the API database fetch every second?

Thank you.

masch1na
  • 97
  • 5
  • Please show your code in one code block. Where is this `await` done? Is it not in a loop? BTW, that `setInterval` is useless, as each time you throw away the result. – trincot Jun 04 '22 at 14:42

1 Answers1

1

Define your variable outside of fetch function:

function fetchDatabase()
{
  let fetchResult;
  function loop() {
    fetchResult = database.fetch.local(something, apiHost("api.database.com"));
  }
  loop();
  setInterval(loop, 1000);
  return fetchResult;
}

let outsideResult = await fetchDatabase();
vanowm
  • 9,466
  • 2
  • 21
  • 37