【问题标题】:Asynchronous forEach for image convert base64 promise.all用于图像转换 base64 promise.all 的异步 forEach
【发布时间】:2022-01-03 12:39:00
【问题描述】:

我正在使用 React。我想使用 Promise.all 。但我不知道如何使用它。我有一个imageUrls 数组我必须将它们转换为base64Format,当我手动执行此操作时可以,但我如何与forEach 一起使用?或任何其他解决方案?

手动版

const promise1 = new Promise ((resolve) =>{
     setTimeout(resolve,1000, 'test');
 )}
const promise2 = this.getBase64ImageFromURL("example image url");
const promise3 = this.getBase64ImageFromURL("example image url 2");

Promise.all([promise1,promise2,promise3]).then((res)=>{
   console.log(res)
 )}

我有一个 Url 数组,我必须转换为 base64 但forEach 不等待我如何实现结构?

const imageUrls = ["exampleimageurl1", "exampleimageurl2", "exampleimageurl3"];

imageUrls.forEach((url)=> {
  this.getBase64ImageFromURL(url);
 )}
getBase64ImageFromURL(url) {
    return new Promise((resolve, reject) => {
      var convertedImage = new Image();
      convertedImage.setAttribute('crossOrigin', 'anonymous');
      convertedImage.onload = () => {
        var canvas = document.createElement('canvas');
        canvas.width = convertedImage.width;
        canvas.height = convertedImage.height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(convertedImage, 0, 0);
        var dataURL = canvas.toDataURL('image/png');
        resolve(dataURL);
      };
      convertedImage.onerror = error => {
        reject(error);
      };
      convertedImage.src = url;
    });
  }

【问题讨论】:

  • forEach doesn't wait,好吧,平心而论,forEach 内部没有任何机制,也没有任何尝试来等待承诺解决。没有.then(),没有await,所以无论如何......

标签: javascript arrays reactjs promise


【解决方案1】:

正确,forEach 对承诺一无所知,不会等待任何事情解决。

您可能希望将mapPromise.all 一起使用:

Promise.all(imageUrls.map((url) => this.getBase64ImageFromURL(url)))
.then(results => {
    // ...use `results` array here...
})
.catch(error => {
    // ...handle/report error here...
});

【讨论】:

  • 这是作品谢谢你
猜你喜欢
  • 2022-01-19
  • 2015-12-09
  • 1970-01-01
  • 2020-01-21
  • 2015-12-18
  • 1970-01-01
  • 2020-11-16
  • 1970-01-01
  • 2014-04-06
相关资源
最近更新 更多