setInterval 中的异步调用,其中每个下一个都依赖于上一个

Async calls within setInterval where every next is dependent on previous

我有一个 setInterval 内部调用 API 的设置。根据 api 的响应,我管理 previousState & currentState 变量。

我需要确保每个下一个 setInterval 的东西发生在前一个已经通过变量更新的时候。

我该怎么做?

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

您可以创建一个 sleep 函数,然后在其完成后调用 fetchData

而不是 setInterval
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);

您可以添加一个 while 循环来重复调用 api 函数:

let previous = null;
let current = null;

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


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


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

getStats();