javascript - 如何在reactjs中使用await每2分钟调用一次操作

标签 javascript reactjs async-await es6-promise

我正在使用 async wait 来在 React 中调用 API,我的问题是如何每 2 分钟调用一次 get 服务,因为在我的情况下,promise 没有解决其花费时间并显示挂起状态,所以我想调用如果 promise 未得到解决,每 2 分钟获得一次服务。有人可以指导我如何使用等待来做到这一点。

这是我所做的代码。

export function fetchUser(id) {
  return async dispatch => {
    let userUrl = FETCH_USER_URL + id;
    let response1 = await get(userUrl); // I want to call this again if response not getting within a 2 minutes

    if (response1.status === 200) {

       let processUrl = FETCH_PROCESS_USER_URL;
       let response2 = await get(processUrl);
    if (response2.status === 200) {
       console.log("fetch process user success");
    } else {
       console.log("fetch process user failed");
    }
      console.log("success");
    } else {
      console.log("failed");
    }
  };
}

任何帮助将不胜感激。提前致谢

最佳答案

你可以试试这个

const timeout = setTimeout(fetchUser(id), 120000);

let response = await get(url);

clearTimeout(timeout);

因评论而编辑:

export function fetchUser(id) {
  return async dispatch => {
    let url = FETCH_USER_URL + id;
    const timeout = setTimeout(fetchUser(id), 120000); // start 2 min timer that will call the function again in 2 min

    let response = await get(url); // if response not getting within a 2 minutes call again

    clearTimeout(timeout); //remove it if you get a response before 2min


    if (response.status === 200) {

       let url2 = FETCH_PROCESS_USER_URL;
       let response2 = await get(url);
    if (response2.status === 200) {
       console.log("fetch process user success");
    } else {
       console.log("fetch process user failed");
    }
      console.log("success");
    } else {
      console.log("failed");
    }
  };
}
,,,

关于javascript - 如何在reactjs中使用await每2分钟调用一次操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105179/

相关文章:

javascript - 如何使用它获得选择器

javascript - 如何获取PDF文件的页数?

javascript - 触发器和 ui 部分子类化 View 子类

javascript - 从列表数组中追加一个值 - React Native

reactjs - 无法让highlight.js突出显示React渲染的代码

javascript - 主干模型默认值 : null ? 空字符串?空数组?

javascript - 如何将父组件的输入集中到子组件上?

c# - 异步任务取消最佳实践 : user versus program

asynchronous - 有没有办法避免等待返回流的异步方法?

c# - 对 asmx 服务的异步/等待调用