Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Last active February 25, 2023 16:52
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 prof3ssorSt3v3/cc8a76663e559d4a6d811c4020c3d12b to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/cc8a76663e559d4a6d811c4020c3d12b to your computer and use it in GitHub Desktop.
Code Sample for Saving an array of files in the cache and Retrieving an array of files from the cache
const names = ['sheldon', 'amy', 'penny', 'leonard', 'raj', 'buffy', 'howard', 'bernadette'];
const DEMO = {
cacheref: null,
cachename: 'gelatenous-cube',
cacheReady: false, //change to true after files are saved in the cache
init() {
//build a bunch of files and save them in the cache
//then read all the files from the cache
DEMO.addListeners();
DEMO.checkCache();
},
addListeners() {
document.getElementById('btnCreate').addEventListener('click', DEMO.saveFiles);
document.getElementById('btnRead').addEventListener('click', DEMO.readFiles);
},
checkCache() {
//figure out if there is already something in the cache when the page loads
caches.open(DEMO.cachename).then((cache) => {
DEMO.cacheref = cache;
console.log('cache opened');
cache.keys().then((keys) => {
if (keys.length > 0) {
DEMO.cacheReady = true;
DEMO.readFiles();
} else {
console.warn('Nothing in the cache.');
}
});
});
},
buildFile(name) {
let id = crypto.randomUUID();
let obj = { id, name };
let file = new File([JSON.stringify(obj)], `${id}.json`, { type: 'application/json' });
return file;
},
saveFiles(ev) {
ev && ev.preventDefault();
//create an array of files and array of requests plus responses to save
let files = names.map((name) => DEMO.buildFile(name));
let req_resp = files.map((file) => ({ req: new Request(file.name), resp: new Response(file, { status: 200 }) }));
//save them all in the cache
caches
.open(DEMO.cachename)
.then((cache) => {
DEMO.cacheref = cache;
//save the responses in the cache using the request/response array
//calling cache.put() inside array.map() will create an array of promises
//wrap that in Promise.all()
return Promise.all(req_resp.map((data) => cache.put(data.req, data.resp)));
})
.then(() => {
//all the files are saved
DEMO.cacheReady = true;
console.log('Files saved in cache');
});
},
readFiles(ev) {
ev && ev.preventDefault();
if (DEMO.cacheReady) {
DEMO.cacheref
.keys()
.then((keys) => {
//keys is the list of requests
//we use cache.match on each key... but this is an array of promises
//so we need to wrap that in Promise.all
return Promise.all(keys.map((key) => DEMO.cacheref.match(key)));
})
.then((responses) => {
//responses is an array of responses
return Promise.all(responses.map((resp) => resp.json()));
})
.then((objects) => {
//objects is an array of all the data from all the responses from the previous step
//loop through these and add them to the main element
let main = document.querySelector('main');
main.innerHTML = objects
.map((obj) => {
return `<p><pre>${JSON.stringify(obj)}</pre></p>`;
})
.join('');
});
} else {
console.warn('Cache must be prepared first');
}
},
};
document.addEventListener('DOMContentLoaded', DEMO.init);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Promise All</title>
<script src="app.js"></script>
</head>
<body>
<header>
<h1>Using Promise.all()</h1>
<h2>Opening a list of files and getting their contents</h2>
</header>
<nav>
<button id="btnCreate">Create and Save Multiple Files</button>
<button id="btnRead">Read and Display ALL Files</button>
</nav>
<main>
<!-- file contents will go here -->
</main>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment