Skip to content

Instantly share code, notes, and snippets.

@koseki
Last active April 11, 2021 02:48
Show Gist options
  • Save koseki/c964ec15719a18e02d0f3576be6634de to your computer and use it in GitHub Desktop.
Save koseki/c964ec15719a18e02d0f3576be6634de to your computer and use it in GitHub Desktop.
Memoized Async Function
import axios from 'axios'
class App {
constructor() {
this.cache = {}
}
/**
* 何もキャッシュしないバージョン
*/
async request1(url) {
return await axios.get(url)
}
/**
* API の結果をキャッシュするバージョン
*/
async request2(url) {
if (!this.cache[url]) {
this.cache[url] = await axios.get(url)
}
return this.cache[url]
}
/**
* Promise をキャッシュするバージョン
*/
async request3(url) {
if (!this.cache[url]) {
this.cache[url] = axios.get(url)
}
return this.cache[url]
}
/**
* API を使って何かするメソッド
*/
async doSomethingWithAPI(url, index) {
const result = await this.request3(url)
console.log(index, result.data)
}
async main() {
const url = 'http://localhost:8000/api/test.json'
for (let i = 0; i < 10; i++) {
await this.sleep(1)
this.doSomethingWithAPI(url, i)
}
}
async sleep(msec) {
return new Promise(resolve => setTimeout(resolve, msec))
}
}
const app = new App()
app.main()
{
"name": "memoized-async-function",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"type": "module",
"dependencies": {
"axios": "^0.21.1"
},
"scripts": {
"start": "node index.js",
"server": "node server.js"
}
}
import http from 'http'
const port = 8000
let count = 0
http.createServer(async (req, res) => {
// 少しタイミングを遅らせるため、console.log() を出力します。
console.log(new Date(), req.url)
count += 1
res.writeHead(200, {'Content-Type': 'application/json'})
res.write(`{"count": ${count}}`)
res.end()
}).listen(port)
console.log(`Server running at http://localhost:${port}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment