[英]Timing issue in map / forEach while waiting for promise
因此,我遇到了時間問題。 發生的情況是toDataUrl在chrome.storage.local.get
之前沒有完成。 dataUrl准備好后,如何重構地圖或其他循環? 我嘗試了異步等待,將forEach更改為地圖,反之亦然。 我也嘗試了while循環和計數器,但是也許我沒有正確實現它?
需要說明的是:一旦所有循環都完全完成(目前還沒有發生), chrome.storage.local.get
需要調用chrome.storage.local.get
。
前往資料網址:
const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
}))
主體:
app.checkOfflineStorage = function(quotes) {
let nQuotes = quotes;
nQuotes.data.map(function(e, idx) {
if(e.attachments) {
e.attachments.data.forEach(function(el) {
if(el.type === 'quote-picture') {
toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {
el.dataURI = res;
})
}
})
}
if(e.title) {
if(typeof e.title.data.attachments !== 'undefined') {
var title_attachments = e.title.data.attachments.data;
title_attachments.forEach(function(el) {
toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`).then(function(res) {
el.dataURI = res;
})
})
}
}
})
chrome.storage.local.get('offlineCache',
if (Object.keys(storedQuoteArray).length === 0) {
console.log(nQuotes)
chrome.storage.local.set({"offlineCache": nQuotes}, function(res) {});
} else {
console.log(nQuotes)
var combinedArray = storedQuoteArray.offlineCache.data.concat(nQuotes.data)
combinedArray = combinedArray.slice(0, 100)
console.log('100', combinedArray)
chrome.storage.local.set({"offlineCache": {"data": combinedArray}}, function(res) {});
}
})
}
Promise.all
的快速示例:
Promise.all(e.attachments.data.map(function(el) {
if(el.type === 'quote-picture') {
return toDataURL(`https://quotecatalog.imgix.net${el.value}?w=110`)
}
);)
.then(function (resultArray) {
// Handle results array
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.