我最近不得不在没有后端端点的情况下创建一个用户界面 (UI)。重点是使 UI 尽可能响应,以便用户可以知道操作何时正在进行。
这主要意味着当进行 AJAX 调用时,UI 应进行指示,并在调用完成时进行相应更新。
为了帮助 UI 的开发,我创建了一个函数来模拟 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 < 0 || probability > 1) { resolve(result); return; } const hit = Math.random(); if (hit < probability) { resolve(result); } else { reject( `Placeholder rejection (${Math.round( hit * 100 )}%) - this should NOT appear in production` ); } }, timeout); }); }
要使用此功能:
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: 'user1@example.com', 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 < 0 || probability > 1 ) { resolve(result); return; } const hit = Math.random(); console.log(hit, probability); if (hit < probability) { resolve(result); } else { reject( `Placeholder rejection (${Math.round( hit * 100 )}%) - this should NOT appear in production` ); } }, timeout); }); }
这篇文章首次发布于 cheehow.dev
以上是AJAX 调用的占位符函数的详细内容。更多信息请关注PHP中文网其他相关文章!