Home > front end >  Async calls within setInterval where every next is dependent on previous
Async calls within setInterval where every next is dependent on previous

Time:05-15

I have a setInterval setup which internally calls an API. Based on the api response I manage previousState & currentState variables.

I need to make sure that every next setInterval stuff happens when the previous has updated by variables already.

How can I do it?

let previous = null;
let current = null;

const fakeApi = () => {
  return new Promise((resolve) => setTimeout(resolve(1), 3000));
};

async function fetchData() {
  current = await fakeApi();
  callB(previous, current);
  previous = current;
}

function getStats(cb) {
  setInterval(fetchData, 3000);
}

function callB(prev, curr) {
  console.log(prev   " >>> "   curr);
}

getStats(callB);

CodePudding user response:

Instead of setInterval, you could create an sleep function and then call the fetchData after its finished

let previous = null;
let current = null;

const fakeApi = () => {
  return new Promise((resolve) => setTimeout(resolve(1), 3000));
};
const sleep = (ms) => new Promise(res => setTimeout(res, ms));

async function fetchData() {
  current = await fakeApi();
  callB(previous, current);
  previous = current;
  await sleep(3000);
  return fetchData()
}


function callB(prev, curr) {
  console.log(prev   " >>> "   curr);
}

getStats(callB);

CodePudding user response:

You could add a while loop to repeatedly call the api function:

let previous = null;
let current = null;

const fakeApi = async () => {
   return new Promise((resolve) => setTimeout(resolve(1), 3000));
};


let getStats = async ()=>{
  while(true) {
      await fakeApi()
      callB(previous, current);
      previous = current;
      await new Promise((resolve) => setTimeout(resolve(1), 3000)); //add delay between updates as required
  }
})()


function callB(prev, curr) {
  console.log(prev   " >>> "   curr);
}

getStats();
  • Related