Me gustaría que esta función se ejecutara cada 5 segundos y obtuviera nuevos datos. La función getGas() es una función async-await en sí misma y funciona bien si solo llamo let gas = await getGas(); . El problema es que necesito que se ejecute cada 5 segundos y obtenga un nuevo precio de gasolina. Tengo problemas para entender cómo llamar a esta función y hacer que se ejecute cada 5 segundos.
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 }hmm... Simplemente haría que setTimeout una Promise en sí mismo y luego tendría gas como una async function para llamar...
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()" } Sin embargo, si simplemente no formuló su pregunta correctamente y desea que el gas variable se actualice cada 5 segundos en ese bloque de código dentro de la recuperación principal
una async function para llamar ..
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" }EDITAR : me dijiste que no funciona, así que doy un ejemplo en vivo y ahora pregunto cómo
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();Si desea usar setTimeout para eso, la devolución de llamada debe invocar la función que llama a setTimeout nuevamente, por ejemplo
(async function main() { const gas = await getGas(); // do stuff with gas setTimeout(main, 5000); // call main again after 5 seconds }());Su setTimeout no necesita estar envuelto en su propia función async . Simplemente llame a main , registre los datos y luego vuelva a llamar a main .
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();