Home Web Front-end JS Tutorial Placeholder function for AJAX calls

Placeholder function for AJAX calls

Aug 22, 2024 pm 06:57 PM

Placeholder function for AJAX calls

I recently had to create a user-interface (UI) without the backend endpoints in place. The focus was on making the UI as responsive as possible so that the user can tell when an action is underway.

This mostly means that when an AJAX call is made, the UI should indicate so, and update correspondingly when the call completes.

To help with the development of the UI, I created a function to simulate AJAX calls. The function is able to:

  • accept a delay (in milliseconds) to simulate the delay from making an actual AJAX call
  • accept a probability of failing to simulate when an AJAX call fails
  • return a supplied payload

The TypeScript code is below (see the gist for the complete code sample with the docstring):

export async function delay<T>(
  timeout: number,
  probability?: number,
  result?: T
): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    setTimeout(() => {
      if (!probability || probability < 0 || probability > 1) {
        resolve(result);
        return;
      }

      const hit = Math.random();
      if (hit < probability) {
        resolve(result);
      } else {
        reject(
          `Placeholder rejection (${Math.round(
            hit * 100
          )}%) - this should NOT appear in production`
        );
      }
    }, timeout);
  });
}
Copy after login

To use this function:

async function handleButtonClick() {
  // Update the UI to show a loading indicator.

  try {
    // highlight-start
    // Make the call take 3 seconds, with a 10% chance of failure,
    // and return an array of users.
    const result = await delay(3000, 0.9, [
      {
        email: 'user1@example.com',
        username: 'User 1',
      },
    ]);
    // highlight-end

    // Update the UI when the call completes succesfully.
  } catch (err: any) {
    // Update the UI when the call fails.
  }
}
Copy after login

The JavaScript version of the same function below:

export async function delay(timeout, probability, result) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (
        !probability ||
        typeof probability !== 'number' ||
        probability < 0 ||
        probability > 1
      ) {
        resolve(result);
        return;
      }

      const hit = Math.random();
      console.log(hit, probability);
      if (hit < probability) {
        resolve(result);
      } else {
        reject(
          `Placeholder rejection (${Math.round(
            hit * 100
          )}%) - this should NOT appear in production`
        );
      }
    }, timeout);
  });
}
Copy after login

This post was first published at cheehow.dev

The above is the detailed content of Placeholder function for AJAX calls. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

Custom Google Search API Setup Tutorial

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

Example Colors JSON File

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

8 Stunning jQuery Page Layout Plugins

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

Build Your Own AJAX Web Applications

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

What is 'this' in JavaScript?

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

10 Mobile Cheat Sheets for Mobile Development

See all articles