Home > Net >  SetTimeout for an async await function fo retrieve new data
SetTimeout for an async await function fo retrieve new data

Time:10-09

I would this function to run every 5 seconds and get new data. The getGas() function is an async-await function in and of itself and works fine if I just call let gas = await getGas();. The issue is that I need it to run every 5 seconds and get a new gas price. I'm having trouble understanding how to call this function and have it run every 5 seconds.

async function main() {
  // get the current gwei prices & new price every 5 seconds

  let gas = async () => {
    setTimeout(() => {
      await getGas();
    }, 5000);
  };

  console.log(gas);

  // other code down here
}

CodePudding user response:

If you want to use setTimeout for that then the callback needs to invoke the function that calls setTimeout again, e.g.

(async function main() {
  const gas = await getGas();
  // do stuff with gas

  setTimeout(main, 5000); // call main again after 5 seconds
}());

CodePudding user response:

hmm.. I would just make the setTimeout a Promise in itself and then have gas as an async function to call..

async function main() {
  // get the current gwei prices & new price every 5 seconds

  let gas = async () => {
    return new Promise(r=>{
      setTimeout(() => {  r(await getGas())  }, 5e3);
    )}
  }

  console.log(await gas()); //whatever getGas should be

  // other code down here

  //whenever you want gas, you can just "await gas()"
}

However.. if you just didn't word your question correctly and you want the variable gas to be updated every 5 seconds in that block of code within recalling main

an async function to call..

async function main() {
  // get the current gwei prices & new price every 5 seconds

  let gas = null; //starting value
  setInterval(async()=>gas=await getGas(),5e3); //every 5 seconds, gas is updated

  console.log(gas); //null
  setTimeout(()=>console.log(gas),6e3); //whatever getGas should be
  // other code down here

  //whenever you want gas, you can just "gas"
}

CodePudding user response:

You can use the setInterval function instead:

setInterval(async () => {
  await getGas();
}, 5000)

CodePudding user response:

Your setTimeout doesn't need to be wrapped in its own async function. Just call main, log the data, and then call main again.

function mockApi(page) {
  return new Promise((res, rej) => {
    setTimeout(() => res(page), 1000);
  });
}

async function main(page = 1) {
  const data = await mockApi(page);
  console.log(`Data: ${data}`);
  setTimeout(main, 1000,   page);
}

main();

  • Related