Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@YSRKEN
Last active October 21, 2018 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YSRKEN/261d16940f60d49e052238a194d82944 to your computer and use it in GitHub Desktop.
Save YSRKEN/261d16940f60d49e052238a194d82944 to your computer and use it in GitHub Desktop.
JavaScriptの非同期処理をキャッシュする場合の注意点 ref: https://qiita.com/YSRKEN/items/f808ef7597b95bdc5879
// Angularを知らない人向けの説明:
// AngularにはHttpClientクラスがあり、それを使うことでGETなどのHTTPリクエストが実行できる。
// また、コンストラクタの引数にするだけでDI(依存性の注入)できる
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
private async getHoge(): Promise<string> {
return await this.http.get<string>(url).toPromise();
}
// 簡単なキャッシュ
cache: {[key: string]: string} = {};
private async getHoge(): Promise<string> {
// キャッシュにあればそちらを返す
if ("getHoge" in this.cache){
return this.cache["getHoge"];
}
// キャッシュに無いのでHTTPリクエストし、その結果をキャッシュする
const result = await this.http.get<string>(url).toPromise();
this.cache["getHoge"] = result;
return result;
}
// 簡単なキャッシュ
cache: {[key: string]: string} = {};
// セマフォ
semaphore: boolean = false;
private async getHoge(): Promise<string> {
// キャッシュにあればそちらを返す
if ("getHoge" in this.cache){
return this.cache["getHoge"];
}
// セマフォが立っている際は通信中なので、読み込みを待機する
if (this.semaphore) {
// 適当な時間(今回は100ミリ秒)待機する
await new Promise(resolve => setTimeout(resolve, 100));
// 再帰的に処理を呼び出す
return this.getHoge();
}
// キャッシュに無いのでHTTPリクエストし、その結果をキャッシュする
this.semaphore = true;
const result = await this.http.get<string>(url).toPromise();
this.cache["getHoge"] = result;
this.semaphore = false;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment