JavaScript and TypeScript course ยท Module 4: Asynchronous JavaScript

HTTP Request Handling - Practical Patterns and Advanced Techniques

29 min read ยท
In this lesson9

In the previous exercise we covered the basics of the Fetch API. Now let's expand our knowledge with more advanced techniques and practical patterns to build a robust communication system for our Jurassic Park.

Comprehensive Error Handling

In an environment as critical as Jurassic Park, where a system failure could lead to dangerous situations, proper error handling in HTTP communication is extremely important. Let's create a more advanced error handling mechanism:

async function safeRequest(url, options = {}) {
  const controller = new AbortController();
  const { signal } = controller;

  // Set timeout (10 seconds)
  const timeoutId = setTimeout(() => controller.abort(), 10000);

  try {
    const response = await fetch(url, { ...options, signal });
    clearTimeout(timeoutId);

    // HTTP error categories
    if (response.status >= 500) {
      throw new Error('Server error, attemptNumbly a temporary issue.');
    } else if (response.status === 404) {
      throw new Error('Resource not found.');
    } else if (response.status === 403) {
      throw new Error('No permission to access this resource.');
    } else if (response.status === 401) {
      throw new Error('Authentication required. Please log in again.');
    } else if (!response.ok) {
      throw new Error(`Unexpected HTTP error: ${response.status}`);
    }

    // Handle different response types
    const contentType = response.headers.get('content-type');
    if (contentType && contentType.includes('application/json')) {
      return await response.json();
    } else if (contentType && contentType.includes('text/')) {
      return await response.text();
    } else {
      return await response.blob();
    }
  } catch (error) {
    clearTimeout(timeoutId);

    // Handle different error types
    if (error.name === 'AbortError') {
      throw new Error('Request aborted - time limit exceeded (10s).');
    } else if (!navigator.onLine) {
      throw new Error('No internet connection. Check your network connection.');
    } else {
      console.error('Error details:', error);
      throw new Error(`Error communicating with server: ${error.message}`);
    }
  }
}

Retry Pattern - Automatic Request Retries

In the Jurassic Park network, temporary connectivity issues can occur, especially in remote parts of the island. Let's implement an automatic retry mechanism for failed requests:

/**
 * Executes an HTTP request with automatic retries
 * @param {Function} requestFn - Function performing the request, returning a Promise
 * @param {Object} options - Configuration options
 * @returns {Promise} - Request result or last error after exhausting attempts
 */
async function withRetry(requestFn, options = {}) {
  const {
    maxAttempts = 3,
    initialDelay = 1000,
    delayFactor = 2,
    maxDelay = 10000,
    timeoutMs = 10000,
    shouldRetry = (error) => {
      // By default retry only for server errors (5xx) and network issues
      return (
        error.message.includes('Server error') ||
        error.message.includes('No internet') ||
        error.name === 'AbortError'
      );
    }
  } = options;

  let lastError;
  let attemptNum = 0;

  while (attemptNum <= maxAttempts) {
    try {
      // For each attempt, create a new abort controller
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), timeoutMs);

      // If it's not the first attempt, wait before retrying
      if (attemptNum > 0) {
        const delayTime = Math.min(
          initialDelay * Math.pow(delayFactor, attemptNum - 1),
          maxDelay
        );
        console.log(`Attempt ${attemptNum}/${maxAttempts} failed. Retrying in ${delayTime}ms...`);
        await new Promise(resolve => setTimeout(resolve, delayTime));
      }

      // Execute the request
      const result = await requestFn(controller.signal);
      clearTimeout(timeoutId);
      return result;
    } catch (error) {
      clearTimeout(timeoutId);
      lastError = error;

      // Check whether to retry
      if (attemptNum === maxAttempts || !shouldRetry(error)) {
        break;
      }

      attemptNum++;
    }
  }

  // Throw the last error after exhausting all attempts
  throw new Error(`Failed after ${maxAttempts} attempts: ${lastError.message}`);
}

// Usage example
async function fetchDinosaurInfo(id) {
  return withRetry(
    async (signal) => {
      const response = await fetch(`https://api.jurassic-park.com/dinosaurs/${id}`, { signal });

      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }

      return response.json();
    },
    {
      maxAttempts: 5,
      initialDelay: 500,
      shouldRetry: (error) => error.message.includes('HTTP Error: 5')
    }
  );
}

Request Queuing and Concurrent Connection Limits

In situations where we need to make many HTTP requests but want to limit the number of simultaneous connections so we don't overload the network or server, we can implement request queuing:

class TaskQueue {
  constructor(maxConcurrency = 3) {
    this.maxConcurrency = maxConcurrency;
    this.activeTasks = 0;
    this.queue = [];
  }

  async add(task) {
    // If there's room for more parallel tasks, execute immediately
    if (this.activeTasks < this.maxConcurrency) {
      return this.execute(task);
    }

    // Otherwise add to the queue
    return new Promise((resolve, reject) => {
      this.queue.push({ task, resolve, reject });
    });
  }

  async execute(task) {
    this.activeTasks++;

    try {
      // Execute the task
      const result = await task();
      return result;
    } catch (error) {
      throw error;
    } finally {
      this.activeTasks--;
      this.processNext();
    }
  }

  processNext() {
    if (this.queue.length === 0 || this.activeTasks >= this.maxConcurrency) {
      return;
    }

    // Get the next task from the queue
    const { task, resolve, reject } = this.queue.shift();

    // Execute the task and forward the result to the waiting Promise
    this.execute(task)
      .then(resolve)
      .catch(reject);
  }
}

// Example usage of the queue to monitor many dinosaurs
async function monitorAllDinosaurs(idList) {
  const queue = new TaskQueue(5); // Max 5 concurrent requests
  const results = [];
  const errors = [];

  // Helper functions for tracking progress
  const totalTasks = idList.length;
  let completedTasks = 0;

  function updateProgress() {
    completedTasks++;
    const percent = Math.floor((completedTasks / totalTasks) * 100);
    console.log(`Monitoring progress: ${percent}% (${completedTasks}/${totalTasks})`);
  }

  // Create an array of Promises for all tasks
  const promises = idList.map(id => {
    return queue.add(async () => {
      try {
        console.log(`Monitoring dinosaur #${id}...`);
        const result = await fetchDinosaurInfo(id);
        results.push(result);
        updateProgress();
        return result;
      } catch (error) {
        errors.push({ id, error: error.message });
        updateProgress();
        throw error;
      }
    }).catch(error => {
      // Catch errors so we don't interrupt the entire process
      console.error(`Error monitoring dinosaur #${id}:`, error.message);
    });
  });

  // Wait for all tasks to finish
  await Promise.all(promises);

  return {
    results,
    errors,
    summary: {
      total: totalTasks,
      success: results.length,
      error: errors.length
    }
  };
}

Cache Data Management (Caching)

In Jurassic Park we have data that changes rarely (e.g., dinosaur species) and data that changes frequently (e.g., dinosaur locations). Implementing a cache will help optimize communication:

class CacheManager {
  constructor() {
    this.cache = new Map();
    this.stats = {
      hits: 0,
      misses: 0,
      invalidations: 0
    };
  }

  /**
   * Retrieves data from cache or executes the fetch function if data is not cached
   * @param {string} key - Unique data identifier in cache
   * @param {Function} fetchFn - Function to fetch data if not in cache
   * @param {Object} options - Cache options
   * @returns {Promise} - Promise with data
   */
  async get(key, fetchFn, options = {}) {
    const {
      ttl = 60000, // Default TTL: 1 minute
      forceRefresh = false, // Whether to force refresh despite being cached
      onlyIfCached = false // Whether to return only from cache (no network request)
    } = options;

    // Check if data is in cache and still valid
    const entry = this.cache.get(key);
    const now = Date.now();

    if (entry && !forceRefresh && now < entry.expiresAt) {
      // Data found in cache and still valid
      this.stats.hits++;
      return entry.data;
    }

    // If we only want cached data and there's none, return null
    if (onlyIfCached) {
      return null;
    }

    // Data not in cache or we're forcing a refresh
    this.stats.misses++;

    try {
      // Fetch data
      const data = await fetchFn();

      // Save in cache
      this.cache.set(key, {
        data,
        expiresAt: now + ttl,
        addedAt: now
      });

      return data;
    } catch (error) {
      // If we have stale data in cache, we can return it as a fallback
      if (entry) {
        console.warn(`Error fetching data for ${key}, using stale data from cache:`, error);
        return entry.data;
      }

      // Otherwise propagate the error
      throw error;
    }
  }

  /**
   * Invalidates cache entries matching a pattern
   * @param {string|RegExp} pattern - Pattern to match cache keys
   */
  invalidate(pattern) {
    const isString = typeof pattern === 'string';
    let count = 0;

    for (const key of this.cache.keys()) {
      if (isString ? key.includes(pattern) : pattern.test(key)) {
        this.cache.delete(key);
        count++;
      }
    }

    this.stats.invalidations += count;
    return count;
  }

  /**
   * Clears all cache entries
   */
  clear() {
    const count = this.cache.size;
    this.cache.clear();
    this.stats.invalidations += count;
    return count;
  }

  /**
   * Returns cache usage statistics
   */
  getStats() {
    const totalRequests = this.stats.hits + this.stats.misses;
    const hitRate = totalRequests === 0 ? 0 : this.stats.hits / totalRequests;

    return {
      ...this.stats,
      totalRequests,
      hitRate: hitRate.toFixed(2),
      activeEntries: this.cache.size
    };
  }
}

// Create a cache manager instance
const dinosaurCache = new CacheManager();

// Usage example
async function fetchDinosaurInfoWithCache(id, options = {}) {
  return dinosaurCache.get(
    `dino-${id}`,
    async () => {
      const response = await fetch(`https://api.jurassic-park.com/dinosaurs/${id}`);
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }
      return response.json();
    },
    {
      ttl: 300000, // 5 minutes for dinosaur data
      ...options
    }
  );
}

// Function to invalidate cache after an update
async function updateDinosaur(id, data) {
  const response = await fetch(`https://api.jurassic-park.com/dinosaurs/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });

  if (!response.ok) {
    throw new Error(`Update error: ${response.status}`);
  }

  // Invalidate this dinosaur's cache
  dinosaurCache.invalidate(`dino-${id}`);

  // Also invalidate dinosaur lists that might contain this dinosaur
  dinosaurCache.invalidate('dino-list');

  return response.json();
}

// Fetch dinosaur list with shorter cache (data changes more frequently)
async function getDinosaurList(filter = {}) {
  const queryParams = new URLSearchParams(filter).toString();
  const cacheKey = `dino-list-${queryParams || 'all'}`;

  return dinosaurCache.get(
    cacheKey,
    async () => {
      const url = `https://api.jurassic-park.com/dinosaurs?${queryParams}`;
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }
      return response.json();
    },
    { ttl: 60000 } // 1 minute for dinosaur lists
  );
}

Server-Synchronized Request Handling

In Jurassic Park we sometimes need to perform operations that require server synchronization, such as updating dinosaur health statuses. Let's implement a mechanism that ensures data is saved even when connectivity issues occur:

class SyncQueue {
  constructor(options = {}) {
    // localStorage key for storing the queue
    this.key = options.key || 'dinosaurs-sync-queue';

    // Load saved queue
    this.queue = this.loadQueue();

    // Flag indicating whether synchronization is active
    this.isSyncing = false;

    // Auto-start synchronization
    if (options.autoSync !== false) {
      this.startSync();
    }

    // Listen for online/offline state changes
    window.addEventListener('online', () => {
      console.log('Connection restored. Starting synchronization...');
      this.startSync();
    });

    window.addEventListener('offline', () => {
      console.log('Connection lost. Synchronization paused.');
    });
  }

  /**
   * Loads the queue from localStorage
   */
  loadQueue() {
    try {
      const savedQueue = localStorage.getItem(this.key);
      return savedQueue ? JSON.parse(savedQueue) : [];
    } catch (error) {
      console.error('Error loading sync queue:', error);
      return [];
    }
  }

  /**
   * Saves the queue to localStorage
   */
  saveQueue() {
    try {
      localStorage.setItem(this.key, JSON.stringify(this.queue));
    } catch (error) {
      console.error('Error saving sync queue:', error);
    }
  }

  /**
   * Adds an operation to the sync queue
   * @param {string} url - Request URL
   * @param {Object} options - Fetch options
   * @param {string} type - Operation type (e.g. 'health-update')
   * @returns {string} - Operation ID in the queue
   */
  addToQueue(url, options = {}, type = 'unknown') {
    const id = `op-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

    this.queue.push({
      id,
      url,
      options,
      type,
      addedAt: new Date().toISOString(),
      attempts: 0
    });

    this.saveQueue();
    this.startSync();

    return id;
  }

  /**
   * Starts the synchronization process
   */
  async startSync() {
    // If already syncing or no connection, do nothing
    if (this.isSyncing || !navigator.onLine || this.queue.length === 0) {
      return;
    }

    this.isSyncing = true;

    try {
      let index = 0;
      while (index < this.queue.length) {
        const operation = this.queue[index];

        try {
          console.log(`Synchronizing operation: ${operation.type} (${operation.id})`);

          // Increment attempt count
          operation.attempts++;
          this.saveQueue();

          // Execute the request
          const response = await fetch(operation.url, operation.options);

          if (!response.ok) {
            throw new Error(`HTTP Error: ${response.status}`);
          }

          // Operation succeeded, remove from queue
          this.queue.splice(index, 1);
          this.saveQueue();

          console.log(`Operation ${operation.id} synchronized successfully`);

          // Don't increment index since we removed the element
        } catch (error) {
          console.error(`Error synchronizing operation ${operation.id}:`, error);

          // If we've reached max attempts, mark as failed
          if (operation.attempts >= 5) {
            console.warn(`Operation ${operation.id} exceeded retry limit. Marking as failed.`);
            operation.status = 'failed';
            operation.errorMessage = error.message;
            this.saveQueue();
          }

          // Move to next operation
          index++;
        }
      }
    } finally {
      this.isSyncing = false;

      // If there are still items in the queue, retry in 1 minute
      if (this.queue.some(op => !op.status || op.status !== 'failed')) {
        setTimeout(() => this.startSync(), 60000);
      }
    }
  }

  /**
   * Removes failed operations from the queue
   */
  clearFailedOperations() {
    const previousCount = this.queue.length;
    this.queue = this.queue.filter(op => !op.status || op.status !== 'failed');
    this.saveQueue();
    return previousCount - this.queue.length;
  }

  /**
   * Returns the current queue status
   */
  getStatus() {
    const total = this.queue.length;
    const failed = this.queue.filter(op => op.status === 'failed').length;
    const pending = total - failed;

    return {
      total,
      pending,
      failed,
      isSyncing: this.isSyncing
    };
  }
}

// Create sync queue instance
const dinosaurSyncQueue = new SyncQueue({
  key: 'jurassic-park-dino-sync'
});

// Usage example: updating dinosaur health that will be synchronized
function updateDinosaurHealth(id, healthParams) {
  // Prepare data for sending
  const data = {
    id,
    health: healthParams.health,
    lastCheckTime: new Date().toISOString(),
    symptoms: healthParams.symptoms || [],
    updatedBy: 'dr-wu'
  };

  // If we're online, try immediately
  if (navigator.onLine) {
    return fetch(`https://api.jurassic-park.com/dinosaurs/${id}/health`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }
      return response.json();
    })
    .catch(error => {
      console.warn('Failed to update health online, adding to sync queue');

      // Add to sync queue
      dinosaurSyncQueue.addToQueue(
        `https://api.jurassic-park.com/dinosaurs/${id}/health`,
        {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        },
        `health-update-${id}`
      );

      // Return data as if the operation succeeded, though it will be synced later
      return {
        ...data,
        pendingSync: true
      };
    });
  } else {
    // If we're offline, add to queue immediately
    dinosaurSyncQueue.addToQueue(
      `https://api.jurassic-park.com/dinosaurs/${id}/health`,
      {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      },
      `health-update-${id}`
    );

    return Promise.resolve({
      ...data,
      pendingSync: true
    });
  }
}

Authentication and Token Refresh

In the Jurassic Park system we need to secure access to the API using authentication tokens. Let's implement a mechanism that automatically refreshes the token when it expires:

class AuthManager {
  constructor() {
    this.tokenAccessKey = 'jp-access-token';
    this.tokenRefreshKey = 'jp-refresh-token';
    this.expiryKey = 'jp-token-expiry';
    this.refreshInProgress = false;
    this.refreshListeners = [];
  }

  /**
   * Gets the current access token
   * @param {boolean} autoRefresh - Whether to auto-refresh the token if expired
   * @returns {Promise<string>} - Promise with the access token
   */
  async getAccessToken(autoRefresh = true) {
    const token = localStorage.getItem(this.tokenAccessKey);
    const expiry = localStorage.getItem(this.expiryKey);

    // Check if token exists and hasn't expired
    if (token && expiry) {
      const expiryDate = new Date(expiry);
      const now = new Date();

      // Add 1-minute buffer to avoid using a token that's about to expire
      const bufferTime = 60 * 1000; // 1 minute in milliseconds

      if (expiryDate.getTime() - now.getTime() > bufferTime) {
        return token;
      }

      // Token has expired or will expire soon
      if (autoRefresh) {
        return this.refreshToken();
      }
    }

    throw new Error('No valid access token');
  }

  /**
   * Refreshes the access token using the refresh token
   * @returns {Promise<string>} - Promise with the new access token
   */
  async refreshToken() {
    // If a refresh is already in progress, wait for its result
    if (this.refreshInProgress) {
      return new Promise((resolve, reject) => {
        this.refreshListeners.push({ resolve, reject });
      });
    }

    this.refreshInProgress = true;

    try {
      const refreshToken = localStorage.getItem(this.tokenRefreshKey);

      if (!refreshToken) {
        throw new Error('No refresh token');
      }

      const response = await fetch('https://api.jurassic-park.com/auth/refresh', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refresh_token: refreshToken })
      });

      if (!response.ok) {
        if (response.status === 401) {
          // Refresh token is invalid, log the user out
          this.logout();
          throw new Error('Session expired. Please log in again.');
        }
        throw new Error(`Token refresh error: ${response.status}`);
      }

      const data = await response.json();

      // Save new tokens
      localStorage.setItem(this.tokenAccessKey, data.access_token);
      localStorage.setItem(this.tokenRefreshKey, data.refresh_token);

      // Calculate expiry time
      const expiry = new Date();
      expiry.setSeconds(expiry.getSeconds() + data.expires_in);
      localStorage.setItem(this.expiryKey, expiry.toISOString());

      // Notify all waiting listeners
      this.refreshListeners.forEach(listener => {
        listener.resolve(data.access_token);
      });

      this.refreshListeners = [];
      return data.access_token;
    } catch (error) {
      // On error, notify all waiting listeners
      this.refreshListeners.forEach(listener => {
        listener.reject(error);
      });

      this.refreshListeners = [];
      throw error;
    } finally {
      this.refreshInProgress = false;
    }
  }

  /**
   * Saves tokens after login
   * @param {Object} authData - Authentication data
   */
  saveTokens(authData) {
    localStorage.setItem(this.tokenAccessKey, authData.access_token);
    localStorage.setItem(this.tokenRefreshKey, authData.refresh_token);

    // Calculate expiry time
    const expiry = new Date();
    expiry.setSeconds(expiry.getSeconds() + authData.expires_in);
    localStorage.setItem(this.expiryKey, expiry.toISOString());
  }

  /**
   * Logs the user out
   */
  logout() {
    localStorage.removeItem(this.tokenAccessKey);
    localStorage.removeItem(this.tokenRefreshKey);
    localStorage.removeItem(this.expiryKey);
  }

  /**
   * Checks if the user is logged in
   * @returns {boolean}
   */
  isLoggedIn() {
    return !!localStorage.getItem(this.tokenAccessKey);
  }
}

// Create auth manager instance
const auth = new AuthManager();

// Usage example - function for making authenticated requests
async function authenticatedRequest(url, options = {}) {
  try {
    // Get access token (with auto-refresh)
    const token = await auth.getAccessToken();

    // Add token to headers
    const authOptions = {
      ...options,
      headers: {
        ...options.headers,
        'Authorization': `Bearer ${token}`
      }
    };

    // Execute request
    const response = await fetch(url, authOptions);

    // Handle authorization errors
    if (response.status === 401) {
      // Try refreshing the token and retrying
      try {
        const newToken = await auth.refreshToken();

        // Retry request with new token
        const refreshedOptions = {
          ...options,
          headers: {
            ...options.headers,
            'Authorization': `Bearer ${newToken}`
          }
        };

        return fetch(url, refreshedOptions);
      } catch (refreshError) {
        // Token refresh failed, log user out
        auth.logout();
        window.location.href = '/login'; // Redirect to login
        throw new Error('Session expired. Please log in again.');
      }
    }

    return response;
  } catch (error) {
    console.error('Authenticated request error:', error);
    throw error;
  }
}

// Usage example
async function fetchEnclosureData(enclosureId) {
  const response = await authenticatedRequest(
    `https://api.jurassic-park.com/paddocks/${enclosureId}`
  );

  if (!response.ok) {
    throw new Error(`Error fetching enclosure data: ${response.status}`);
  }

  return response.json();
}

// Login function
async function login(email, password) {
  try {
    const response = await fetch('https://api.jurassic-park.com/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });

    if (!response.ok) {
      throw new Error(`Login error: ${response.status}`);
    }

    const authData = await response.json();

    // Save tokens
    auth.saveTokens(authData);

    return {
      success: true,
      user: authData.user
    };
  } catch (error) {
    console.error('Login error:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

File Upload with Progress

In Jurassic Park we often need to upload large files, such as images or videos from dinosaur monitoring cameras. Let's implement a function that handles file uploads with progress reporting:

/**
 * Sends a file to the server with progress monitoring
 * @param {File} file - File to send
 * @param {string} url - Target URL
 * @param {Object} options - Additional options
 * @returns {Promise} - Promise with operation result
 */
async function sendFile(file, url, options = {}) {
  return new Promise((resolve, reject) => {
    // Default options
    const {
      method = 'POST',
      fieldName = 'file',
      additionalData = {},
      onProgress = null,
      onError = null,
      maxRetries = 3
    } = options;

    // Retry counter
    let attempts = 0;

    // Function to execute the upload
    function performUpload() {
      // Create XHR object
      const xhr = new XMLHttpRequest();

      // Configure event handlers
      xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable && typeof onProgress === 'function') {
          const percent = Math.round((event.loaded / event.total) * 100);
          onProgress({
            loaded: event.loaded,
            total: event.total,
            percent
          });
        }
      });

      xhr.addEventListener('load', () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            // Parse JSON response
            const responseData = JSON.parse(xhr.responseText);
            resolve(responseData);
          } catch (e) {
            resolve({
              success: true,
              status: xhr.status,
              message: xhr.statusText
            });
          }
        } else {
          const error = new Error(`HTTP Error: ${xhr.status}`);
          error.status = xhr.status;
          error.statusText = xhr.statusText;

          if (xhr.status >= 500 && attempts < maxRetries) {
            // For server errors, retry
            attempts++;
            console.warn(`File upload error (${xhr.status}). Retry attempt ${attempts}/${maxRetries}...`);
            setTimeout(performUpload, 2000 * attempts); // Increasing delay between attempts
          } else {
            if (typeof onError === 'function') {
              onError(error);
            }
            reject(error);
          }
        }
      });

      xhr.addEventListener('error', () => {
        const error = new Error('Network error during file upload');
        if (typeof onError === 'function') {
          onError(error);
        }

        if (attempts < maxRetries) {
          attempts++;
          console.warn(`Network error during upload. Retry attempt ${attempts}/${maxRetries}...`);
          setTimeout(performUpload, 2000 * attempts);
        } else {
          reject(error);
        }
      });

      xhr.addEventListener('abort', () => {
        const error = new Error('File upload was aborted');
        if (typeof onError === 'function') {
          onError(error);
        }
        reject(error);
      });

      // Open connection
      xhr.open(method, url, true);

      // Prepare FormData
      const formData = new FormData();
      formData.append(fieldName, file);

      // Add additional data
      Object.entries(additionalData).forEach(([key, value]) => {
        formData.append(key, value);
      });

      // Send request
      xhr.send(formData);

      // Return object with abort method
      return {
        abort: () => xhr.abort()
      };
    }

    // Start uploading
    performUpload();
  });
}

// Usage example
async function sendCameraFootage(file, location) {
  const controller = document.getElementById('upload-controller');
  const progressBar = document.getElementById('upload-progress');
  const statusText = document.getElementById('upload-status');

  controller.classList.remove('hidden');
  statusText.textContent = 'Preparing...';

  try {
    const result = await sendFile(
      file,
      'https://api.jurassic-park.com/security/camera-footage',
      {
        additionalData: {
          location: location,
          timestamp: new Date().toISOString(),
          operator: 'dr-wu'
        },
        onProgress: (info) => {
          progressBar.value = info.percent;
          statusText.textContent = `Uploading: ${info.percent}%`;
        },
        onError: (error) => {
          statusText.textContent = `Error: ${error.message}`;
          progressBar.classList.add('error');
        }
      }
    );

    statusText.textContent = 'Upload complete!';
    progressBar.value = 100;

    setTimeout(() => {
      controller.classList.add('hidden');
    }, 3000);

    return result;
  } catch (error) {
    statusText.textContent = `Error: ${error.message}`;
    progressBar.classList.add('error');
    throw error;
  }
}

Network State Monitoring

In Jurassic Park we must be prepared for connectivity issues, especially in remote parts of the island. Let's implement a network state monitoring system:

class NetworkMonitor {
  constructor(options = {}) {
    this.listeners = {
      change: [],
      online: [],
      offline: []
    };

    this.lastPing = null;
    this.delayTime = null;
    this.status = navigator.onLine ? 'online' : 'offline';
    this.endpointUrl = options.endpointPing || 'https://api.jurassic-park.com/ping';
    this.pingIntervalMs = options.pingIntervalMs || 30000; // 30 seconds
    this.pingTimeout = options.pingTimeout || 5000; // 5 seconds

    // Add listeners for online/offline events
    window.addEventListener('online', this.handleOnline.bind(this));
    window.addEventListener('offline', this.handleOffline.bind(this));

    // Start regular pinging
    if (options.autostartPing !== false) {
      this.startPinging();
    }
  }

  /**
   * Handles transition to online mode
   */
  handleOnline() {
    const previousStatus = this.status;
    this.status = 'online';

    // Notify listeners
    this.notifyListeners('online');

    if (previousStatus !== this.status) {
      this.notifyListeners('change', { status: this.status, previous: previousStatus });
    }

    // Perform immediate ping to check real connectivity
    this.ping();
  }

  /**
   * Handles transition to offline mode
   */
  handleOffline() {
    const previousStatus = this.status;
    this.status = 'offline';
    this.delayTime = null;

    // Notify listeners
    this.notifyListeners('offline');

    if (previousStatus !== this.status) {
      this.notifyListeners('change', { status: this.status, previous: previousStatus });
    }
  }

  /**
   * Pings the server to check real connectivity
   * @returns {Promise<number>} - Promise with latency in ms
   */
  async ping() {
    if (!navigator.onLine) {
      this.delayTime = null;
      return Promise.reject(new Error('Browser is in offline mode'));
    }

    try {
      const startTime = Date.now();

      // Set timeout for fetch
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), this.pingTimeout);

      const response = await fetch(`${this.endpointUrl}?t=${startTime}`, {
        method: 'GET',
        cache: 'no-store',
        signal: controller.signal
      });

      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status}`);
      }

      // Calculate latency
      const endTime = Date.now();
      this.delayTime = endTime - startTime;
      this.lastPing = new Date();

      // Update status
      const previousStatus = this.status;
      this.status = 'online';

      if (previousStatus !== this.status) {
        this.notifyListeners('change', { status: this.status, previous: previousStatus });
        this.notifyListeners('online');
      }

      return this.delayTime;
    } catch (error) {
      // If timeout or network error, mark as offline
      if (error.name === 'AbortError' || error instanceof TypeError) {
        const previousStatus = this.status;
        this.status = 'offline';
        this.delayTime = null;

        if (previousStatus !== this.status) {
          this.notifyListeners('change', { status: this.status, previous: previousStatus });
          this.notifyListeners('offline');
        }
      }

      throw error;
    }
  }

  /**
   * Starts regular server pinging
   */
  startPinging() {
    // Stop existing interval if any
    this.stopPinging();

    // Perform first ping immediately
    this.ping().catch(e => console.warn('Initial ping error:', e));

    // Set ping interval
    this.pingInterval = setInterval(() => {
      this.ping().catch(e => console.warn('Ping error:', e));
    }, this.pingIntervalMs);
  }

  /**
   * Stops regular server pinging
   */
  stopPinging() {
    if (this.pingInterval) {
      clearInterval(this.pingInterval);
      this.pingInterval = null;
    }
  }

  /**
   * Adds an event listener
   * @param {string} eventType - Event type ('change', 'online', 'offline')
   * @param {Function} callback - Callback function
   */
  on(eventType, callback) {
    if (this.listeners[eventType]) {
      this.listeners[eventType].push(callback);
    }
    return this; // For chain API
  }

  /**
   * Removes a listener
   * @param {string} eventType - Event type
   * @param {Function} callback - Callback function to remove
   */
  off(eventType, callback) {
    if (this.listeners[eventType]) {
      this.listeners[eventType] = this.listeners[eventType].filter(cb => cb !== callback);
    }
    return this;
  }

  /**
   * Notifies listeners about an event
   * @param {string} eventType - Event type
   * @param {Object} data - Event data
   */
  notifyListeners(eventType, data = {}) {
    if (this.listeners[eventType]) {
      this.listeners[eventType].forEach(callback => {
        try {
          callback({
            type: eventType,
            timestamp: new Date(),
            status: this.status,
            delayTime: this.delayTime,
            ...data
          });
        } catch (e) {
          console.error(`Error in listener ${eventType}:`, e);
        }
      });
    }
  }

  /**
   * Returns current network state
   */
  getState() {
    return {
      status: this.status,
      delayTime: this.delayTime,
      lastPing: this.lastPing,
      browserOnline: navigator.onLine
    };
  }
}

// Create network monitor instance
const networkMonitor = new NetworkMonitor();

// Usage example
networkMonitor.on('change', (info) => {
  console.log(`Network state change: ${info.previous} -> ${info.status}`);

  // Update UI
  const statusIndicator = document.getElementById('network-status');
  if (statusIndicator) {
    statusIndicator.className = `status-${info.status}`;
    statusIndicator.textContent = info.status === 'online'
      ? `Online (ping: ${info.delayTime}ms)`
      : 'Offline';
  }
});

networkMonitor.on('offline', () => {
  // Show notification to user
  showNotification('Lost network connection', 'error');

  // Enable offline mode in the app
  app.enableOfflineMode();
});

networkMonitor.on('online', (info) => {
  showNotification(`Connection restored (ping: ${info.delayTime}ms)`, 'success');

  // Sync data with server
  dinosaurSyncQueue.startSync();

  // Disable offline mode
  app.disableOfflineMode();
});

function showNotification(text, type) {
  const notification = document.createElement('div');
  notification.className = `notification ${type}`;
  notification.textContent = text;

  document.body.appendChild(notification);

  // Remove notification after 5 seconds
  setTimeout(() => {
    notification.classList.add('fade-out');
    setTimeout(() => {
      document.body.removeChild(notification);
    }, 500);
  }, 5000);
}

Summary - Building a Comprehensive API Client

By combining all the techniques discussed, we can create a highly efficient, error-resilient, and user-friendly API communication system. Here's a complete solution:

/**
 * Comprehensive API client for the Jurassic Park system
 */
class JurassicAPIClient {
  constructor(options = {}) {
    // Base URL configuration
    this.baseUrl = options.baseUrl || 'https://api.jurassic-park.com';

    // Initialize auth manager
    this.auth = new AuthManager();

    // Initialize cache
    this.cache = new CacheManager();

    // Initialize sync queue
    this.syncQueue = new SyncQueue({
      key: 'jp-sync-queue',
      autoSync: true
    });

    // Initialize network monitor
    this.networkMonitor = new NetworkMonitor({
      endpointPing: `${this.baseUrl}/ping`,
      pingIntervalMs: 30000
    });

    // Monitor network state
    this.networkMonitor.on('online', () => {
      this.syncQueue.startSync();
    });

    // Default request options
    this.defaultOptions = {
      timeout: 30000,
      retries: 3,
      cacheTime: 300000, // 5 minutes
      useCache: true
    };
  }

  /**
   * Executes an HTTP request
   * @param {string} endpoint - API endpoint
   * @param {Object} options - Request options
   * @returns {Promise} - Promise with request result
   */
  async request(endpoint, options = {}) {
    // Merge default options with provided ones
    const {
      method = 'GET',
      body,
      headers = {},
      useAuth = true,
      useCache = this.defaultOptions.useCache,
      cacheTime = this.defaultOptions.cacheTime,
      forceRefresh = false,
      timeout = this.defaultOptions.timeout,
      retries = this.defaultOptions.retries,
      offlineFallback = true
    } = options;

    // Prepare cache key
    const cacheKey = `${method}:${endpoint}:${JSON.stringify(body || {})}`;

    // Check if request is in cache (only for GET)
    if (method === 'GET' && useCache && !forceRefresh) {
      try {
        const cachedData = await this.cache.get(
          cacheKey,
          () => {}, // Empty function - we don't want to execute the request yet
          { ttl: cacheTime, onlyIfCached: true }
        );

        if (cachedData) {
          return cachedData;
        }
      } catch (error) {
        // Ignore cache errors
      }
    }

    // Check network state
    if (!this.networkMonitor.getState().status === 'online') {
      // We're offline, check if we have cached data
      if (method === 'GET' && useCache && offlineFallback) {
        try {
          const cachedData = await this.cache.get(
            cacheKey,
            () => {}, // Empty function - we don't want to execute the request yet
            { ttl: Infinity, onlyIfCached: true, ignoreExpiry: true }
          );

          if (cachedData) {
            // Offline mode information
            return {
              ...cachedData,
              _meta: {
                fromCache: true,
                offlineMode: true,
                timestamp: new Date()
              }
            };
          }
        } catch (error) {
          // Ignore cache errors
        }
      }

      // If it's a data-modifying request, add to sync queue
      if (method !== 'GET' && offlineFallback) {
        return this.addToSyncQueue(endpoint, { method, body, headers, useAuth });
      }

      throw new Error('No network connection. Unable to execute request.');
    }

    // Function that executes the actual request
    const executeRequest = async (signal) => {
      // Prepare URL
      const url = `${this.baseUrl}${endpoint}`;

      // Prepare request options
      const requestOptions = {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...headers
        },
        signal
      };

      // Add request body if it exists
      if (body) {
        requestOptions.body = JSON.stringify(body);
      }

      // Add auth token if required
      if (useAuth) {
        try {
          const token = await this.auth.getAccessToken();
          requestOptions.headers['Authorization'] = `Bearer ${token}`;
        } catch (error) {
          // If unable to get token and request requires auth
          throw new Error('Not authenticated. Please log in again.');
        }
      }

      // Execute request with timeout
      const controller = new AbortController();
      const { signal: abortSignal } = controller;
      if (signal) {
        // If an external signal was passed, combine it with ours
        signal.addEventListener('abort', () => controller.abort());
      }

      const timeoutId = setTimeout(() => controller.abort(), timeout);
      requestOptions.signal = abortSignal;

      try {
        const response = await fetch(url, requestOptions);
        clearTimeout(timeoutId);

        // Handle HTTP errors
        if (response.status === 401 && useAuth) {
          // Try refreshing the token
          try {
            await this.auth.refreshToken();
            // Retry with new token
            return this.request(endpoint, options);
          } catch (refreshError) {
            throw new Error('Session expired. Please log in again.');
          }
        }

        if (!response.ok) {
          const error = new Error(`HTTP Error: ${response.status}`);
          error.status = response.status;
          error.statusText = response.statusText;

          // Try to get error details from response
          try {
            const errorData = await response.json();
            error.data = errorData;
            error.message = errorData.message || error.message;
          } catch (e) {
            // Ignore parsing errors
          }

          throw error;
        }

        // Parse response depending on type
        const contentType = response.headers.get('content-type');
        let data;

        if (contentType && contentType.includes('application/json')) {
          data = await response.json();
        } else if (contentType && contentType.includes('text/')) {
          data = await response.text();
        } else {
          data = await response.blob();
        }

        // Save response in cache for GET requests
        if (method === 'GET' && useCache) {
          this.cache.get(cacheKey, () => data, { ttl: cacheTime, forceRefresh: true });
        }

        return data;
      } catch (error) {
        clearTimeout(timeoutId);

        if (error.name === 'AbortError') {
          throw new Error(`Request aborted after timeout (${timeout}ms)`);
        }

        throw error;
      }
    };

    // Execute request with retries
    return withRetry(
      (signal) => executeRequest(signal),
      {
        maxAttempts: retries,
        initialDelay: 1000,
        delayFactor: 2,
        timeoutMs: timeout
      }
    );
  }

  /**
   * Adds a request to the sync queue (offline mode)
   * @param {string} endpoint - API endpoint
   * @param {Object} options - Request options
   * @returns {Promise} - Promise with temporary result
   */
  addToSyncQueue(endpoint, options) {
    const { method, body } = options;

    // Generate unique operation ID
    const operationId = `op-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

    // Add to sync queue
    this.syncQueue.addToQueue(
      `${this.baseUrl}${endpoint}`,
      {
        method,
        headers: {
          'Content-Type': 'application/json',
          // Token will be added during actual synchronization
        },
        body: body ? JSON.stringify(body) : undefined
      },
      `${method}-${endpoint}`
    );

    // Return temporary response
    return Promise.resolve({
      _meta: {
        pendingSync: true,
        operationId,
        timestamp: new Date(),
        offlineMode: true
      },
      ...body // Return passed data as temporary result
    });
  }

  // Helper methods for different request types

  /**
   * Executes a GET request
   */
  async get(endpoint, options = {}) {
    return this.request(endpoint, { ...options, method: 'GET' });
  }

  /**
   * Executes a POST request
   */
  async post(endpoint, body, options = {}) {
    return this.request(endpoint, { ...options, method: 'POST', body });
  }

  /**
   * Executes a PUT request
   */
  async put(endpoint, body, options = {}) {
    return this.request(endpoint, { ...options, method: 'PUT', body });
  }

  /**
   * Executes a DELETE request
   */
  async delete(endpoint, options = {}) {
    return this.request(endpoint, { ...options, method: 'DELETE' });
  }

  /**
   * Uploads a file to the server
   */
  async uploadFile(endpoint, file, options = {}) {
    const {
      fieldName = 'file',
      additionalData = {},
      onProgress = null,
      useAuth = true
    } = options;

    // If offline, cannot upload files
    if (!this.networkMonitor.getState().status === 'online') {
      throw new Error('Unable to upload file in offline mode.');
    }

    // Prepare FormData
    const formData = new FormData();
    formData.append(fieldName, file);

    // Add additional data
    Object.entries(additionalData).forEach(([key, value]) => {
      formData.append(key, JSON.stringify(value));
    });

    // Request options
    const requestOptions = {
      method: 'POST',
      body: formData
    };

    // Add auth token if required
    if (useAuth) {
      try {
        const token = await this.auth.getAccessToken();
        requestOptions.headers = {
          'Authorization': `Bearer ${token}`
        };
      } catch (error) {
        throw new Error('Not authenticated. Please log in again.');
      }
    }

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();

      xhr.upload.addEventListener('progress', (event) => {
        if (event.lengthComputable && typeof onProgress === 'function') {
          const percent = Math.round((event.loaded / event.total) * 100);
          onProgress({
            loaded: event.loaded,
            total: event.total,
            percent
          });
        }
      });

      xhr.addEventListener('load', () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const responseData = JSON.parse(xhr.responseText);
            resolve(responseData);
          } catch (e) {
            resolve({
              success: true,
              status: xhr.status,
              message: xhr.statusText
            });
          }
        } else {
          const error = new Error(`HTTP Error: ${xhr.status}`);
          error.status = xhr.status;
          error.statusText = xhr.statusText;
          reject(error);
        }
      });

      xhr.addEventListener('error', () => {
        reject(new Error('Network error during file upload'));
      });

      xhr.addEventListener('abort', () => {
        reject(new Error('File upload was aborted'));
      });

      xhr.open('POST', `${this.baseUrl}${endpoint}`, true);

      if (requestOptions.headers) {
        Object.entries(requestOptions.headers).forEach(([key, value]) => {
          xhr.setRequestHeader(key, value);
        });
      }

      xhr.send(formData);
    });
  }

  /**
   * Authenticates the user
   */
  async login(email, password) {
    try {
      const response = await this.request('/auth/login', {
        method: 'POST',
        body: { email, password },
        useAuth: false
      });

      // Save tokens
      this.auth.saveTokens(response);

      return {
        success: true,
        user: response.user
      };
    } catch (error) {
      return {
        success: false,
        error: error.message
      };
    }
  }

  /**
   * Logs the user out
   */
  logout() {
    this.auth.logout();
    // Optionally clear cache on logout
    this.cache.clear();
  }
}

// Create API client instance
const api = new JurassicAPIClient({
  baseUrl: 'https://api.jurassic-park.com'
});

// API client usage examples

// Login
async function loginUser(email, password) {
  const result = await api.login(email, password);
  if (result.success) {
    console.log(`Logged in as ${result.user.name}`);
    return true;
  } else {
    console.error(`Login error: ${result.error}`);
    return false;
  }
}

// Fetch dinosaur data
async function getDinosaur(id) {
  try {
    return await api.get(`/dinosaurs/${id}`);
  } catch (error) {
    console.error(`Failed to fetch dinosaur #${id}:`, error.message);
    throw error;
  }
}

// Update dinosaur data
async function updateDinosaur(id, data) {
  try {
    return await api.put(`/dinosaurs/${id}`, data);
  } catch (error) {
    console.error(`Failed to update dinosaur #${id}:`, error.message);
    throw error;
  }
}

// Fetch dinosaur list with filtering
async function getDinosaurList(filter = {}) {
  try {
    return await api.get('/dinosaurs', {
      body: filter,
      cacheTime: 60000 // Shorter cache for lists (1 minute)
    });
  } catch (error) {
    console.error('Failed to fetch dinosaurs list:', error.message);
    throw error;
  }
}

// Upload dinosaur medical records
async function sendMedicalRecords(dinoId, file, data) {
  const progressBar = document.getElementById('upload-progress');
  const statusText = document.getElementById('upload-status');

  try {
    return await api.uploadFile(`/dinosaurs/${dinoId}/medical-records`, file, {
      additionalData: data,
      onProgress: (info) => {
        if (progressBar) progressBar.value = info.percent;
        if (statusText) statusText.textContent = `Uploading: ${info.percent}%`;
      }
    });
  } catch (error) {
    console.error(`Failed to upload documentation for dinosaur #${dinoId}:`, error.message);
    if (statusText) statusText.textContent = `Error: ${error.message}`;
    throw error;
  }
}

In this comprehensive example, we implemented an advanced API client that handles:

  1. Comprehensive error handling - different types of HTTP and network errors
  2. Automatic request retries - for temporary problems
  3. Response caching - for faster access and offline mode support
  4. Offline operation queuing - to ensure data consistency
  5. Network state monitoring - for making appropriate decisions
  6. Authentication and token refresh - for secure API access
  7. File upload with progress monitoring - for better user experience

Such a comprehensive API client provides resilience against network issues, efficiency through caching, offline mode support, and user-friendly mechanisms like progress monitoring. It is an ideal solution for critical systems like the Jurassic Park management system, where reliability and security are paramount.

In the next lesson, we will look at how to efficiently process JSON data received from the API to present it to users in an accessible way.

Code for this lesson: index.js
// Function Factory - Building functions
console.log("FUNCTION FACTORY - BUILDING FUNCTIONS\n");

// Factory function - a function that creates other functions
function createDinosaurHandler(species, defaultDangerLevel) {
  console.log(`Creating a handler for: ${species}`);

  // We return a new function with "remembered" parameters
  return function(action) {
    console.log(`\n[${species}] Action: ${action}`);
    console.log(`  Default danger: ${defaultDangerLevel}/10`);

    switch(action) {
      case 'FEED':
        console.log(`  Feeding ${species}`);
        break;
      case 'MONITOR':
        console.log(`  Monitoring ${species}`);
        break;
      case 'ALERT':
        console.log(`  ALARM! ${species} needs attention!`);
        break;
      default:
        console.log(`  Unknown action`);
    }
  };
}

// Creating specialized handlers
console.log("=== CREATING HANDLERS ===\n");

const trexHandler = createDinosaurHandler('T-Rex', 10);
const triceratopsHandler = createDinosaurHandler('Triceratops', 3);
const velociraptorHandler = createDinosaurHandler('Velociraptor', 8);

// Using handlers
console.log("\n=== USING HANDLERS ===");

trexHandler('FEED');
trexHandler('MONITOR');

triceratopsHandler('FEED');
velociraptorHandler('ALERT');

// Factory with extra options
console.log("\n=== ADVANCED FACTORY ===\n");

function createAdvancedHandler(config) {
  const {
    species,
    dangerLevel,
    feedingTime,
    maxCapacity
  } = config;

  let currentCount = 0;

  return {
    add: function() {
      if (currentCount < maxCapacity) {
        currentCount++;
        console.log(`Added ${species}. Currently: ${currentCount}/${maxCapacity}`);
        return true;
      } else {
        console.log(`No room for ${species}! (${currentCount}/${maxCapacity})`);
        return false;
      }
    },

    remove: function() {
      if (currentCount > 0) {
        currentCount--;
        console.log(`Removed ${species}. Currently: ${currentCount}/${maxCapacity}`);
        return true;
      } else {
        console.log(`No ${species} to remove`);
        return false;
      }
    },

    getInfo: function() {
      return {
        species,
        dangerLevel,
        feedingTime,
        count: currentCount,
        capacity: maxCapacity,
        occupancy: `${((currentCount / maxCapacity) * 100).toFixed(1)}%`
      };
    },

    feed: function() {
      console.log(`Feeding ${currentCount} x ${species} at ${feedingTime}`);
    }
  };
}

// Creating advanced handlers
const trexManager = createAdvancedHandler({
  species: 'T-Rex',
  dangerLevel: 10,
  feedingTime: '18:00',
  maxCapacity: 5
});

const velociraptorManager = createAdvancedHandler({
  species: 'Velociraptor',
  dangerLevel: 8,
  feedingTime: '16:00',
  maxCapacity: 10
});

console.log("=== POPULATION MANAGEMENT ===\n");

trexManager.add();
trexManager.add();
trexManager.add();

console.log("\nT-Rex Info:", trexManager.getInfo());

trexManager.feed();

console.log("");

velociraptorManager.add();
velociraptorManager.add();
velociraptorManager.add();
velociraptorManager.add();
velociraptorManager.add();

console.log("\nVelociraptor Info:", velociraptorManager.getInfo());

console.log("\n=== BENEFITS OF FACTORY PATTERN ===");
console.log("Encapsulation - hidden internal data");
console.log("Reusability - easy creation of similar objects");
console.log("Customization - each handler can have its own configuration");
console.log("Closures - each handler remembers its settings");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is the retry pattern in the context of HTTP requests?

  2. 2. Which technique is most effective for debugging unhandled errors in a Promise?

Hands-on tasks in the game

  • Code editor

    Write an async function fetchWithRetry(url, maxRetries) that retries fetch after an error with increasing delay.

  • Vertical ordering

    Arrange the stages of the retry pattern with exponential backoff:

  • Click in order

    Arrange the elements of a Promise race:

  • Vertical ordering

    Arrange the execution order of this code: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');

  • Vertical ordering

    Arrange the order in which the Event Loop processes code:

  • Vertical ordering

    Arrange the steps of fetching data from an API:

  1. QuestionRetry Pattern
  2. Coding taskPractice: Retry Pattern with async/await
  3. Put in orderRetry Stages with Exponential Backoff
  4. Click in orderPromise.race Syntax
  5. Put in orderExecution Order: Synchronous vs Asynchronous
  6. QuestionDebugging Asynchronous Code
  7. Put in orderCode Processing by the Event Loop
  8. Put in orderHTTP Request Handling Steps with async/await

Useful articles