Sobes.tech
Middle

Kuidas te suhtlete sündmuste tsükliga (event loop)?

sobes.tech AI

Vastus AI-lt

I do not interact directly with the event loop; it is an internal mechanism of the JavaScript engine (for example, V8 in Node.js and browsers). My interaction is indirect, through asynchronous operations:

Main touchpoints:

  • Timers: setTimeout, setInterval. They enqueue callback tasks that will be executed by the event loop after the specified time.
  • Promises: Promise. Their methods (then, catch, finally) register callbacks that are executed asynchronously in the microtask queue of the event loop.
  • Asynchronous input/output operations: Server requests (fetch, XMLHttpRequest), file system operations in Node.js. Their completion enqueues the corresponding callbacks into the macro task or microtask queue.
  • DOM event handlers: addEventListener. Callbacks are executed when the event loop processes the event that occurred in the DOM.

Example of using promises for an asynchronous operation:

// Asynchronous function
async function fetchData(url) {
  try {
    const response = await fetch(url); // Asynchronous operation
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    const data = await response.json(); // Asynchronous operation
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error; // Propagate error
  }
}

// Calling the asynchronous function and handling the result
fetchData('https://api.example.com/data')
  .then(data => {
    console.log('Received data:', data); // This callback will execute asynchronously
  })
  .catch(error => {
    console.error('An error occurred:', error); // This callback will execute on error
  });

console.log('This code will execute BEFORE the asynchronous operations complete.'); // This code is synchronous

Understanding how the event loop works helps me write non-blocking code, manage asynchronous operations efficiently, and avoid "freezing" the user interface. I am aware that long synchronous operations block the main thread and the event loop, so I try to avoid or offload them to web workers.