首页 > 解决方案 > 从数组中获取 URL 列表并处理它们

问题描述

我正在尝试获取数组中的 URL 列表,然后将它们全部转换为 Base64。然而,我需要阻止函数运行,直到所有图像都被提取和处理,因为下一步需要输出。

预期过程应 let example = ["https://www.example.com/1.jpg", "https://www.example.com/2.jpg"];转换为 Base64 编码数组。

//Contains the B64 encoded images
var observationImages = []
//List of Images to fetch and encode
 var lookupPhotos = ['https://www.example.com/1.jpg', 'https://www.example.com/2.jpg'];

    Promise.all(
            lookupPhotos.map(url => {
                fetch(url)
                    .then(response => response.blob())
                    .then(blob => new Promise((resolve, reject) => {
                        console.log('Converting to b64');
                        const reader = new FileReader()
                        reader.onloadend = () => resolve(reader.result)
                        reader.onerror = reject
                    }))
                    .then(dataUrl => {observationImages.push(dataUrl)});
            }
        )
    ).then(data => {
            console.log('Promises all resolved!');
            console.log(observationImages);
    });

我尝试过使用 Promises,但我不确定我是否完全理解它们是如何工作的,所以它不能按预期工作。

标签: javascriptarrays

解决方案


此代码在我的浏览器中本地运行。

你能看到我改变了什么吗?

  1. 为了清楚起见,在 Promise 链之外声明了您的自定义 Promise 函数

  2. 将 blob 传递给读者。

  3. 在您的地图回调中放置一个返回,以便将承诺存储到数组中(否则您将得到一个空数组)。

  4. resolve 和 reject 是您传递数据的方法。该数据通过承诺链传递。

  5. 您存储在数组中的链需要返回一个承诺。因此,将非承诺代码移至 Promise.all() 解决后。

  6. 最后添加了一个 .catch 。

    // will contain the B64 encoded images
    let observationImages = [];
    //List of Images to fetch and encode
    let photosToLookUp = [
    "https://www.gravatar.com/avatar/a70aa9d494bf438c8b56aced999e897f?s=48&d=identicon&r=PG",
    "https://www.gravatar.com/avatar/e0e123ac05632003d0ff22ec8ce3a554?s=32&d=identicon&r=PG"
    ];
    
    const customPromise = blob => {
         return new Promise((resolve, reject) => {
              console.log("Converting to b64");
              const reader = new FileReader();
              reader.readAsDataURL(blob);
              reader.onloadend = () => {
                  resolve(reader.result);
              };
              reader.onerror = err => {
                   reject(err);
              };
          });
      };
    
    Promise.all(
       photosToLookUp.map(url => {
           return fetch(url)
               .then(response => {
                   return response.blob();
                })
               .then(blob => {
                   return customPromise(blob);
                });
         })
      )
      .then(arrayOfData => {
          console.log("Promises all resolved!");
          arrayOfData.forEach(dataUrl => {
               observationImages.push(dataUrl);
          });
          //there is no return value here because you've gotten all the info from the promise chain and are processing it.
    })
    .catch(err => {
         console.log("error:", err);
     });
    

推荐阅读