Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
polling on a promise to have always fresh data

i'm trying to fetch an endpoint that return a json object to display the result in my app.

this json return a list of online users, so i need to refresh this data every X seconds/minutes.

i've writed this code:

function getJustBlabData(url) {
      return new Promise(resolve => {
          const getData = fetch(url);
          resolve(getData)
      })
    }

    getJustBlabData('https://justblab.com/baxf/widget.php?q=online_usr')
      .then((res) => res.json()
        .then((data) => {
          this.justBlab = data
          this.loading = false
          console.log(this.justBlab)
        })
      )

ive tried with setInterval like:

 function getJustBlabData(url) {
      return new Promise(resolve => {
        setInterval(() => {
          const getData = fetch(url);
          resolve(getData)
        }, 1000)
      })
    }

but i'm doing something wrong, but what?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Firstly, use fetch directly, since your getJustBlabData function is essentially just return fetch(url) wrapped in a new Promise - but since fetch already returns a Promise, there is no need for that code at all

i.e.

function getJustBlabData(url) {
  return new Promise(resolve => {
      const getData = fetch(url);
      resolve(getData)
  })
}
getJustBlabData(url).then ....

is equivalent (but in a lot of ways worse for error handling) to

fetch(url).then ....

If you want to do something every X seconds, do the whole thing in the interval

Like this

setInterval(() => {
  this.loading = true;
  fetch('https://justblab.com/baxf/widget.php?q=online_usr')
  .then((res) => res.json())
  .then((data) => {
      this.justBlab = data;
      this.loading = false;
      console.log(this.justBlab);
  });
}, 1000);

Now, this.justBlab gets updated every second

Note: Also, I've flattened your .then pyramid into a .then chain

to address the situation where requests could take longer than a second

(() => {
    const processBlab = () => {
    this.loading = true;
    fetch('https://justblab.com/baxf/widget.php?q=online_usr')
    .then((res) => res.json())
    .then((data) => {
        this.justBlab = data;
        this.loading = false;
        console.log(this.justBlab);
        setTimeout(() => processBlab(), 1000);
    });
    processBlab();
})();

Only reason I put that all in a IIFE is to preserve this - as there is no context in the question as to what this is

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use a promise to create a "wait" function and the restart the process again (get a new set of data) once that completes. Here I used a 5 second delay between each cycle.

Doing it this way, if the server takes 10 seconds to reply this will do a new request 5 seconds after that response and avoids piling up requests.

let delayMSTime = 5000;
let howMany = 1;

function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

function getJustBlabData(url) {
  return new Promise(resolve => {
    const getData = fetch(url);
    resolve(getData);
  })
}

function GoGetEm(myDelay) {
  getJustBlabData('https://justblab.com/baxf/widget.php?q=online_usr')
    .then((res) => res.json())
    .then((data) => {
      this.justBlab = data;
      this.loading = false;
      console.log(this.justBlab);
    }).then(() => {
      console.log("sleeeping for the "+howMany+" time:" + myDelay);
      sleep(myDelay).then(() => {
      howMany++;
        GoGetEm(myDelay);
        console.clear();
      });
    });
}
GoGetEm(delayMSTime);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda