Reputation: 16436
I need to fetch several files but I don't know how to access the request url once I have their blobs resolved:
paths = ['1.png', '2.png', '3.png']
for (const path of paths) {
fetch(path)
.then(resp => resp.blob())
.then(blob => {
console.log('path: ' + path) <- I need access to the fetch path here
})
.catch((error) => {
console.log(error)
})
}
I need access to the fetch path when the resp.blob() Promise is resolved. How do I get access to the fetch path there?
Upvotes: 0
Views: 132
Reputation: 33787
Below I've simulated the parts of the fetch
API you're using in the code you showed. You can see that it works according to the expectations that you expressed. How long each individual fetch
result takes to settle will determine the order of the console messages. (Keep pressing "Run" to experiment and see different, random results.)
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function delay (ms, value) {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
}
// Fetching in this sim will take between 0 and 1500 ms
function fetch (url) {
return delay(
getRandomInt(0, 1500),
{
blob: () => delay(
getRandomInt(0, 50),
new Blob(),
),
},
)
}
paths = ['1.png', '2.png', '3.png'];
for (const path of paths) {
fetch(path)
.then(resp => resp.blob())
.then(blob => {
console.log('path: ' + path);
})
.catch((error) => {
console.log(error);
})
}
Upvotes: 1