Last active
October 21, 2018 07:27
-
-
Save YSRKEN/261d16940f60d49e052238a194d82944 to your computer and use it in GitHub Desktop.
JavaScriptの非同期処理をキャッシュする場合の注意点 ref: https://qiita.com/YSRKEN/items/f808ef7597b95bdc5879
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 簡単なキャッシュ | |
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 簡単なキャッシュ | |
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