重复API请求,直到新数据到达

时间:2019-02-15 14:51:29

标签: javascript asynchronous promise

我正在为那个努力。 我有旧数据。我想在5秒钟的间隔内调用API,直到获得该数据的新等值。 我正在尝试这样(参见代码内的注释):

const requestTimeout = async(currentData, resolve) => {
  //that's my working call to API ;)
  const { data } = await requestGet(URL.LOTTERIES_LIST);

  // if old data is equal to new data let's try again until the backend API will finally change data to new
  if(currentData === data.newData) {
    this.setTimeout(requestTimeout(currentData, resolve), 5000);
  } else {
    resolve(data.newData);
  }
};

// this is a function which is called from another part of app, I need to return/resolve a new data from here, current Data is just old piece of data 
export function callUntilNewDataArrives(shouldCallAPI, currentData) {
  return new Promise(resolve => {
    if (shouldCallAPI) {
      requestTimeout(currentData, resolve);
    }
  });

正如该应用程序另一部分中的注释所述,我试图像这样简单地使用callUntilNewDataArrives函数:

callUntilNewDataArrives(shouldCallAPI, currentData)
      .then(res => console.log(res));

但是这不起作用。谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我认为问题在于您的对象比较。 使用旧数据解决承诺的唯一可能原因是: if(currentData === data.newData)每次都返回false。 我会在调试器中检查它以确保。