xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

How to use Promise and setTimeout to mock an API call in JavaScript All In One

How to use Promise and setTimeout to mock an API call in JavaScript All In One

如何使用 Promise 和 setTimeout 在 JavaScript 中模拟一个 API 调用

args list version

const getMockData = async (data = '', error = 'unknown server error', delay) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(!!data) {
        resolve({
          type: 'Success ✅',
          data,
        });
      } else {
        reject({
          type: 'Error ❌',
          message: error,
        });
      }
    }, delay || 1000);
  });
}

// test cases
(async () => {
  try {
    const success = await getMockData([1,2,3]);
    console.log(success.data);
  } catch (err) {
    console.log(err.message);
  }
  try {
    const error = await getMockData('', '404 not found error', 3000);
    console.log(error);
  } catch (err) {
    console.log(err.message);
  }
})();

args object version


const getMockData = async (options = {
  data: '',
  error: 'unknown server error',
  delay: null
}) => {
  const {data, error, delay} = options;
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(!!data) {
        resolve({
          type: 'Success ✅',
          data,
        });
      } else {
        reject({
          type: 'Error ❌',
          message: error,
        });
      }
    }, delay || 1000);
  });
}

// test cases
(async () => {
  try {
    const success = await getMockData({data: [1,2,3]});
    console.log(success.data);
  } catch (err) {
    console.log(err.message);
  }
  try {
    const error = await getMockData({error: '404 not found error', delay: 3000});
    console.log(error);
  } catch (err) {
    console.log(err.message);
  }
})();

  1. destructured parameter with default value assignment

function aobject arguments default values

const getMockData = async ({
  data = '',
  error = 'unknown server error',
  delay = null,
}) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if(!!data) {
        resolve({
          type: 'Success ✅',
          data,
        });
      } else {
        reject({
          type: 'Error ❌',
          message: error,
        });
      }
    }, delay || 1000);
  });
}

// test cases
(async () => {
  try {
    const success = await getMockData({data: [1,2,3]});
    console.log(success.data);
  } catch (err) {
    console.log(err.message);
  }
  try {
    const error = await getMockData({error: '404 not found error', delay: 3000});
    console.log(error);
  } catch (err) {
    console.log(err.message);
  }
})();

image

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#destructured_parameter_with_default_value_assignment

https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties

https://stackoverflow.com/questions/894860/set-a-default-parameter-value-for-a-javascript-function

API 请求 timeout 超时重试

js 使用 Promise 实现 Fetch 请求超时重试


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-11-20
 * @modified 2022-03-20
 *
 * @description js 使用 Promise 实现 Fetch 请求超时重试
 * @description
 * @difficulty Medium
 * @complexity O(n)
 * @time O(n)
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/16038719.html
 * @link https://www.cnblogs.com/xgqfrms/p/14016391.html
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

function maxRequest(url = ``, times = 3) {
  // 1. 闭包,保存私有属性
  function autoRetry (url, times) {
    console.log('times = ', times);
    times--;
    // 2. fetch 本身返回值就是 Promise,不需要再次使用 Promise 包裹
    return fetch(url).then(value => {
        if(value.status === 200) {
          console.log(`✅ OK`, value);
          // 3. 手动返回 Promise 的 value, 没有返回值 默认返回 undefined
          return value;
        } else {
          throw new Error(`❌  http code error: ${value.status }`);
        }
      }).catch((err) => {
        console.log(`❌  Error`, err);
        if (times < 1) {
          // 4. 方便后续的 thenable 处理 error
          throw new Error('💩  over max request times!');
        } else {
          // 5. 返回递归方法 
          return autoRetry(url, times);
        }
      });
  }
  // 6. 返回一个 Promise 的结果 (成功 Promise 或失败 Promise)
  return autoRetry(url, times);
}

// error test case
maxRequest(`https://cdn.xgqfrms.xyz/json/badges.js`)
  .then(res => res.json())
  .then(json=> console.log('json =', json))
  .catch(err => console.error(`err =`, err))
  .finally(() => {
      console.log('👻  whatever close loading...');
  });

// sucess test case
maxRequest(`https://cdn.xgqfrms.xyz/json/badges.json`)
  .then(res => res.json())
  .then(json=> console.log('json =', json))
  .catch(err => console.error(`err =`, err))
  .finally(() => {
      console.log('👻  whatever close loading...');
  });

demos


// await new Promise((resolve, reject) => {setTimeout(() => resolve(`OK ✅`), 3000)});
// await new Promise((resolve, reject) => {setTimeout(() => reject(`Error ❌`), 3000)});

;(async () => {
  console.log(`promise delay 3 seconds`)
  // delay
  await new Promise((resolve, reject) => {setTimeout(() => resolve(`OK ✅`), 3000)});
  // await new Promise((resolve, reject) => {setTimeout(() => reject(`Error ❌`), 3000)});
  console.log(`promise delay 3 seconds ✅`)
  const antiCrawler = document.querySelector(`#anti-crawler`);
  if(antiCrawler?.firstElementChild) {
    // auto add original url
    antiCrawler.firstElementChild.href = window.location.href;
    antiCrawler.firstElementChild.innerText = window.location.href;
  }
})();

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://cdn.xgqfrms.xyz/sdk/inject-original-url.js



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-08 20:19  xgqfrms  阅读(10)  评论(2编辑  收藏  举报