I'm new to Javascript and am trying to get Images to dynamically add themselves to 'addCache'.
I will then use this with a service worker to add it to the cache.
My sw.js file looks like this:
var product = [];
fetch('http://localhost:3000/api/products')
.then(res => res.json())
.then(json => product = json)
//Caching Files
var cacheName = 'pwa-v1';
var toCache= [
'/PW1/',
'/PW1/Apps/calculate.js',
'/PW1/Apps/login.js',
'/PW1/Apps/index.js',
'/PW1/index.html',
'/PW1/products.html',
'/PW1/style.css',
];
var productImages = [];
for(var i=0;i<product.length;i++){
productImages.push('/PW1/img/'+product[i].name+'.jpg');
}
var addCache = toCache.concat(productImages);
self.addEventListener('install', function(s) {
.............
.............
.............
My goal is to make the fetch request async, it fetches data from backend and stores it into the product array. I want the for loop to wait for the product, then begin the loop. How can I go about doing this?
The for loop just gets the product name, which is the same as the image name.
At the moment it doesn't add any images to add cache. But it does add the rest of the files.
Any help will be appreciated. Thanks in advance.