最近、バックエンド エンドポイントを配置せずにユーザー インターフェイス (UI) を作成する必要がありました。アクションが進行中であることをユーザーが認識できるように、UI の応答性を可能な限り高めることに重点が置かれました。
これは主に、AJAX 呼び出しが行われたときに UI がそのことを示し、呼び出しが完了したときにそれに応じて更新する必要があることを意味します。
UI の開発を支援するために、AJAX 呼び出しをシミュレートする関数を作成しました。この関数は次のことができます:
TypeScript コードは以下のとおりです (docstring を含む完全なコード サンプルの要点を参照してください)。
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 中国語 Web サイトの他の関連記事を参照してください。