[英]Fetching images synchronously using javascript
我有一個應用程序可以生成已下載圖像的鏈接。
當我單獨使用此代碼(如在單個 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)
})
問題是當我嘗試循環瀏覽多個圖像並嘗試創建指向它們的 localStorage 鏈接時。 所有本地 Storageitems 未定義或 null
我懷疑代碼是在保存本地存儲之前執行的。 我不知道如何將工作代碼應用於同步提取。
嘗試創建所有請求的 map 並使用Promise.all
來解析它們的 URL。
假設您有一個 URL 列表:
const urls = ['url1', 'url2', ...];
創建一個獲取請求的 map,如下所示:
const requests = urls.map((url) => fetch(url).then(resp => resp.blob()));
現在將此請求 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.