How to handle a long asynchronous operation on the client side (virus scan, up to an hour)?
sobes.tech AI
Answer from AI
To handle a long asynchronous operation on the client side, such as virus scanning a file that may take up to an hour, you can use the following approach:
-
Send the file to the server — the client uploads the file and receives a unique task identifier.
-
Periodic status polling — the client sends a request to the server at a set interval (e.g., every 10-30 seconds) to check the scan status.
-
Display progress or status — show the user that the scan is in progress and update the status as responses are received.
-
Handle the result — when the server reports that the scan is complete, display the result (e.g., file is clean or infected).
Example in React using setInterval:
function VirusCheck({ taskId }) {
const [status, setStatus] = React.useState('pending');
React.useEffect(() => {
const interval = setInterval(() => {
fetch(`/api/check-status/${taskId}`)
.then(res => res.json())
.then(data => {
setStatus(data.status);
if (data.status === 'done' || data.status === 'error') {
clearInterval(interval);
}
});
}, 30000); // poll every 30 seconds
return () => clearInterval(interval);
}, [taskId]);
return <div>Scan status: {status}</div>;
}
This approach allows the interface to remain responsive and informs the user about the progress of the long operation.