Skip to content

Instantly share code, notes, and snippets.

@ilyakamens
Created March 14, 2019 15:06
Show Gist options
  • Save ilyakamens/c04dc0d39e155dbe9648e4bba263a9b6 to your computer and use it in GitHub Desktop.
Save ilyakamens/c04dc0d39e155dbe9648e4bba263a9b6 to your computer and use it in GitHub Desktop.
Simplified version of using cached promise
const axios = require('axios');
let cache;
async function foo(x) {
if (cache) {
console.log('using cache', x);
return cache;
}
cache = axios.get('https://jsonplaceholder.typicode.com/users').then((resp) => resp.data[0].name);
console.log('fetching from api', x);
return cache;
}
async function bar(x) {
console.log('first before', x);
const first = await foo(x);
console.log('first after', x, first);
console.log('second before', x);
const second = await foo(x);
console.log('second after', x, second);
}
bar(1);
bar(2);
bar(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment