我最近不得不創(chuàng)建一個(gè)沒(méi)有后端端點(diǎn)的用戶界面(ui)。重點(diǎn)是使 ui 盡可能具有響應(yīng)性,以便用戶可以知道操作何時(shí)正在進(jìn)行。
這主要意味著當(dāng)進(jìn)行 ajax 調(diào)用時(shí),ui 應(yīng)進(jìn)行指示,并在調(diào)用完成時(shí)進(jìn)行相應(yīng)更新。
為了幫助 ui 的開(kāi)發(fā),我創(chuàng)建了一個(gè)函數(shù)來(lái)模擬 ajax 調(diào)用。該功能能夠:
接受延遲(以毫秒為單位)來(lái)模擬進(jìn)行實(shí)際 ajax 調(diào)用的延遲
接受 ajax 調(diào)用失敗時(shí)模擬失敗的概率
返回提供的有效負(fù)載
typescript 代碼如下(請(qǐng)參閱帶有文檔字符串的完整代碼示例的要點(diǎn)):
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. } }
登錄后復(fù)制
相同函數(shù)的 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>這篇文章首次發(fā)表于 cheehow.dev</em></p>
登錄后復(fù)制