我最近不得不創建一個沒有后端端點的用戶界面(ui)。重點是使 ui 盡可能具有響應性,以便用戶可以知道操作何時正在進行。
這主要意味著當進行 ajax 調用時,ui 應進行指示,并在調用完成時進行相應更新。
為了幫助 ui 的開發,我創建了一個函數來模擬 ajax 調用。該功能能夠:
接受延遲(以毫秒為單位)來模擬進行實際 ajax 調用的延遲
接受 ajax 調用失敗時模擬失敗的概率
返回提供的有效負載
typescript 代碼如下(請參閱帶有文檔字符串的完整代碼示例的要點):
export async function delay<t>(
timeout: number,
probability?: number,
result?: t
): promise<t> {
return new promise<t>((resolve, reject) => {
settimeout(() => {
if (!probability || probability 1) {
resolve(result);
return;
}
const hit = math.random();
if (hit
<p>要使用此功能:<br></p>
<pre class="brush:php;toolbar:false">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.
}
}
登錄后復制
相同函數的 javascript 版本如下:
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
<p><em>這篇文章首次發表于 cheehow.dev</em></p>
登錄后復制






