[英]Fetching images synchronously using javascript
I have an app that generated links to images that have been downloaded.我有一个应用程序可以生成已下载图像的链接。
When I use this code on its own (as in a single uri) it works for what I am wanting to achieve, the image path is dynamically created and the local image is created and I can stored it and reference it elsewhere where I need.当我单独使用此代码(如在单个 uri 中)时,它适用于我想要实现的目标,动态创建图像路径并创建本地图像,我可以将其存储并在我需要的其他地方引用它。
var path = getOS() + '' + object.link + '/' + object.icon
var outside
fetch(path)
.then(response => response.blob())
.then(images => {
outside = URL.createObjectURL(images)
localStorage.setItem('stored_img'+ _object.link, outside)
})
The problem is when I try and loop through several images and try to create localStorage links to them.问题是当我尝试循环浏览多个图像并尝试创建指向它们的 localStorage 链接时。 All of the local Storageitems are undefined or null
所有本地 Storageitems 未定义或 null
I suspect that the code is executing before the localstorage is saved.我怀疑代码是在保存本地存储之前执行的。 I do not know how to apply the working code to synchronous fetch.
我不知道如何将工作代码应用于同步提取。
Try creating a map of all requests and use Promise.all
to resolve their URLs.尝试创建所有请求的 map 并使用
Promise.all
来解析它们的 URL。
Let's say you have a list of URLs:假设您有一个 URL 列表:
const urls = ['url1', 'url2', ...];
Create a map of fetch requests like this:创建一个获取请求的 map,如下所示:
const requests = urls.map((url) => fetch(url).then(resp => resp.blob()));
Now pass this request map to Promise.all
:现在将此请求 map 传递给
Promise.all
:
Promise.all(requests).then(responseArr => {
const imagesArr = responseArr.map(image => {
const url = URL.createObjectURL(image);
localStorage.setItem('...', url);
return url;
});
// now you have a list of image urls in imagesArr which you can use. They are also stored in localStorage
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.