Infinite Loop with promise

4

I have serious doubts about this that came to me recently.

I want to make an infinite loop of a request to an API every 15 seconds, but I want the loop to wait for the answer of the promise and then go again 15 seconds.

So, the behavior I'm looking for is something like this:

Request -> (Tiempo aleatorio) -> Repuesta -> (Espera 15 seg) 
-> Request (Comenzando el ciclo nuevamente).

And what I get is ...

Request -> (Tiempo aleatorio) -> Repuesta -> (Espera 15 seg) 
-> Request -> (Tiempo superior a 15 segundos) (Request)...

Make a request without waiting for the previous promise to be fulfilled, that is the problem.

Sample code:

link

If you can help me out, it would be very helpful.

Thank you all.

    
asked by Nelbi Alvarado 09.04.2018 в 17:21
source

1 answer

3

You can use a recursive (asynchronous) function.

First, since we are going to use promises, we are going to perform a couple of functions that make our work easier:

// Se resulve una vez haya pasado el tiempo de espera
const delay = ms => new Promise(res => setTimeout(res, ms))

// Utilizamos fetch para hacer una llamada a la API
const apiCall = url => fetch(url).then(res => res.json())

Finally we create the function that will be continuously calling itself:

async function infiniteApiCalls(url, ms) {
  // Request (Tiempo Aleatorio)
  const result = await apiCall(url)
  // Haz lo que sea con el resultado
  console.log(result)
  // ...
  // Esperar x segundos
  await delay(ms)
  // Request otra vez
  await infiniteApiCalls(url, ms)
}

EXAMPLE

const delay = ms => new Promise(res => setTimeout(res, ms))

const apiCall = url => fetch(url)
  .then(res => res.json())
  // Si no quieres que el loop se pare
  // si hay un error, captura el catch
  // o utilizar try/catch en la función
  .catch(() => 'Error :/')

async function infiniteApiCalls(url, ms) {
  // Request (Tiempo Aleatorio)
  const result = await apiCall(url)
  // Haz lo que sea con el resultado
  console.log(result)
  // ...
  // Esperar x segundos
  await delay(ms)
  
  // Request otra vez
  //infiniteApiCalls(url, ms)

  const fn = infiniteApiCalls.bind(null, url, ms)
  
  setTimeout(fn, 0)
}

infiniteApiCalls('https://jsonplaceholder.typicode.com/posts/1', 15000)
    
answered by 09.04.2018 / 17:51
source