在等待承诺时,map / forEach中的计时问题

时间:2017-11-14 23:32:10

标签: javascript google-chrome-extension

所以我有一个时间问题。发生了什么'toDataUrl在调用chrome.storage.local.get之前没有完成。一旦dataUrl准备就绪,我如何重构以使地图或其他循环继续运行?我已尝试异步等待,将forEach更改为map,反之亦然。我也尝试过循环和计数器,但也许我没有正确实现它?

澄清一下:当所有循环完全完成并且当前没有发生时,需要调用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) {});
  }

   })
   }

1 个答案:

答案 0 :(得分:0)

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
});