"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Placeholder function for AJAX calls

Placeholder function for AJAX calls

Published on 2024-08-26
Browse:129

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(
  timeout: number,
  probability?: number,
  result?: T
): Promise {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (!probability || probability  1) {
        resolve(result);
        return;
      }

      const hit = Math.random();
      if (hit 



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: '[email protected]',
        username: 'User 1',
      },
    ]);
    // highlight-end

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

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  1
      ) {
        resolve(result);
        return;
      }

      const hit = Math.random();
      console.log(hit, probability);
      if (hit 



This post was first published at cheehow.dev

Release Statement This article is reproduced at: https://dev.to/cheehow/placeholder-function-for-ajax-calls-51ap?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3