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);
}
})();
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);
}
})();
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;
}
})();
refs
https://cdn.xgqfrms.xyz/sdk/inject-original-url.js
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17687323.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2022-09-08 手把手的教你如何使用 Vite 搭建一个 React UI 组件库 All In One
2022-09-08 WebAssembly API & MDN All In One
2022-09-08 Apple iPhone 14 Pro 药丸设计看不懂,药丸上面那条屏幕缝隙完全没有用处呀?
2022-09-08 如何把 iPad 作为 Mac 扩展屏幕使用 All In One
2021-09-08 TypeScript & npm All In One
2020-09-08 css text-align-last & text-align
2020-09-08 how to read the 10th line of a text using shell script All In One