简体   繁体   English

使用 async/await 意外执行代码

[英]Unexpected code execution using async/await

I am attempting to convert an array of localhost URLs to base64 strings.我正在尝试将 localhost URL 数组转换为 base64 字符串。

    let uploadedBase64Images = [];
    for (let i = 0; i < urls.length; i++) {
      let img = await fetch(urls[i]);
      let imgBlob = await img.blob();
      let reader = new FileReader();
      
      let base64;
      reader.readAsDataURL(imgBlob);
      reader.onloadend = () => {
        console.log(reader.result)
        base64 = reader.result;
        console.log(base64)
        uploadedBase64Images.push(base64)
      };
    } 

    console.log(uploadedBase64Images)

One thing I noticed is that the console.log(uploadedBase64Images) always prints before console.log(base64) .我注意到的一件事是console.log(uploadedBase64Images)总是在console.log(base64)之前打印。 This code block is wrapped in an async function as well.此代码块也包含在异步 function 中。 I've tried many other ways but at the end of the day, uploadedBase64Images is always empty.我尝试了许多其他方法,但最终, uploadedBase64Images始终为空。

When I move uploadedBase64Images.push(base64) outside of reader.onloadend , ie:当我将 uploadBase64Images.push uploadedBase64Images.push(base64) reader.onloadend之外时,即:

    reader.onloadend = () => {
        console.log(reader.result)
        base64 = reader.result;
        console.log(base64)
    };
    uploadedBase64Images.push(base64)

uploadedBase64Images is [undefined] , which leads me to believe that the Promise isn't being resolved? uploadedBase64Images[undefined] ,这让我相信 Promise 没有得到解决?

I appreciate any help on this, thanks in advance!感谢您对此的任何帮助,在此先感谢!

From what i see, the problem is the reader.onloadend , it is in its own zone which is not following the async behaviour.据我所知,问题是reader.onloadend ,它在自己的区域中,不遵循异步行为。

So, by wrapping the reader function to Promise to wait for its response before doing anything may solve your problem因此,通过将阅读器 function 包装到 Promise 等待其响应,然后再执行任何操作可能会解决您的问题

// wrapping reader in Promise
const convertImageToBase64 = async(imgBlob) => {
  return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(imgBlob);
      reader.onloadend = () => {
        resolve(reader.result);
      };
      reader.onerror = reject
  })
}

const uploadedBase64Images = [];
for (let i = 0; i < urls.length; i++) {
  const img = await fetch(urls[i]);
  const imgBlob = await img.blob();
  const base64 = await convertImageToBase64(imgBlob)
  uploadedBase64Images.push(base64)
} 
console.log(uploadedBase64Images)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM