我正在使用 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/