我正在尝试使用 typescript 在 React 中实现轮询功能。轮询函数需要进行 REST API 调用来读取 DynamoDB 中的记录,并继续每 30 秒轮询一次,直到记录中的“状态”字段为“成功”。
我尝试过的代码:
const poll = async function (fn: () => Promise<any>, fnCondition: (result: any) => boolean, ms: number): Promise<any> {
let result = await fn();
while (fnCondition(result)) {
await wait(ms);
result = await fn();
}
return result;
};
const wait = async function (ms = 1000): Promise<void> {
console.log('in wait function');
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
function callPolling(resJson: any): any {
try {
response = await fetch(url, {
method: 'POST',
body: JSON.stringify(request_data),
headers: { 'Content-Type': 'application/json' },
});
} catch (e: unknown) {
console.error(e);
}
return response;
}
const fetchRecord = callPolling(resJson);
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const validate = (result: { body: { Status: string } }) => result.body.Status === 'Success';
const responsePoll = await poll(fetchRecord, validate, 30000);
我看到前端只能查询一次DDB。当它尝试“轮询”时,会抛出
Uncaught (in promise) TypeError: t is not a function
400 异常。
我究竟做错了什么?我可以通过这种方式实现轮询吗?或者有更好的方法吗?
我是 React 和构建 Web 应用程序的新手,因此我正在关注我阅读的一些博客来执行轮询。如果我能得到任何帮助来理解我做错了什么,我将不胜感激。
你可以做一件简单的事情来代替。