Home > Mobile >  How to get resault in iteration in portions, one by one?
How to get resault in iteration in portions, one by one?

Time:09-17

I have function handler, this function handle input(files) converts files from .heic to .jpeg (it's async handle). I need to get the resault one by one(so i can show first photo, when it will be done, while the rest of photo would still handling... and so on!) But whith my code, I wait for all files, and then I get all this files in one time.

Here is my code (ReactJS). Please help me with it.

    for (let i = 0; i < files.length; i  ) {
    
          //Случай когда в инпут попадает файл формата HEIC
          if (files[i].name.includes(".HEIC") || files[i].name.includes(".heic")){
    
            var fileReader = new FileReader()
    
            fileReader.onloadend = async function (e) {
              var arrayBuffer = e.target.result
              var fileType = "image/heic"
              var blob = arrayBufferToBlob(arrayBuffer, fileType)
              console.log(blob)
              const image = await heic2any({
                blob,
                toType: "image/jpeg",
                quality: 0.2,})
    
              var url = URL.createObjectURL(image);
    
    fileReader.readAsArrayBuffer(files[i])
}

CodePudding user response:

I would first promisify the readAsArrayBuffer method:

const promiseArrayBuffer = (file) => new Promise((resolve) => {
    var fileReader = new FileReader();
    fileReader.onloadend = (e) => resolve(e.target.result);
    fileReader.readAsArrayBuffer(file);
});

And then

(async function () {
    for (const file of files) {
        if (!file.name.includes(".HEIC") && !file.name.includes(".heic")) continue;
        const arrayBuffer = await promiseArrayBuffer(file);
        const fileType = "image/heic"
        const blob = arrayBufferToBlob(arrayBuffer, fileType);
        const image = await heic2any({
            blob,
            toType: "image/jpeg",
            quality: 0.2,
        });
        const url = URL.createObjectURL(image);

        // ...etc ... //

    }
})();
  • Related