Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
SetTimeout for an async await function fo retrieve new data

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
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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(async()=>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"
}

EDIT: you told me it doesn't work so I give a live example and am now asking how

async function getGas(){
  return Math.floor(Math.random()*5)
}

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

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

  setInterval(async()=>
    console.log(await gas(),"~ main1") //whatever getGas should be
  ,1e3);
  // other code down here

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

async function main2() {
  // 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
  setInterval(()=>
    console.log(gas,"~ main2") //whatever getGas should be
  ,1e3);
  // other code down here

  //whenever you want gas, you can just "gas"
}
main1(); main2();

about 4 years ago · Juan Pablo Isaza Relatório

0

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
}());
about 4 years ago · Juan Pablo Isaza Relatório

0

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();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda