Sobes.tech
Middle

How to organize asynchronous interaction between frontend and backend during long operations (e.g., starting an evaluation calculation)? How to handle statuses and updates?

sobes.tech AI

Answer from AI

For asynchronous interaction between the frontend and backend during long operations, the following approach is usually used:

  1. The client sends a request to start the operation (e.g., calculating a score).
  2. The server immediately returns a unique task identifier (task ID), and the operation itself runs in the background.
  3. The frontend periodically polls the server using this ID (polling) or subscribes to updates via WebSocket/Server-Sent Events.
  4. The server returns the execution status (e.g., "in progress", "completed", "error") and, if necessary, intermediate results.

Example with polling:

// Start the task
fetch('/start-calculation', { method: 'POST' })
  .then(res => res.json())
  .then(data => {
    const taskId = data.taskId;
    const interval = setInterval(() => {
      fetch(`/task-status/${taskId}`)
        .then(res => res.json())
        .then(statusData => {
          console.log('Status:', statusData.status);
          if (statusData.status === 'completed') {
            clearInterval(interval);
            // handle the result
          }
        });
    }, 2000); // poll every 2 seconds
  });

This approach allows not to block the UI and inform the user about the progress of the operation.