0

I want to convert pictures into base64, add them all to an array and send the array via ajax to my backend. But to my knowledge, the fileReader is async and my code continues before the conversion to a base64-String is done. The problem is that the FileReader doesn't seem to be done when it comes to use the array (and send this to the backend). console.log(speisekarten[0]) gives undefined console.log(speisekarten); is actually the array but that seems to be displayed after the ajax-request

let speisekarten = [];
        let result;
        function fügeHinzu(){
            console.log(result);
            speisekarten.push(result);
        }
        
        function readFile(file){
            let fr = new FileReader();
            fr.onload = function(){
                result = fr.result;
            };
            fr.readAsDataURL(file);
            return; 
        }
        let files = speisekarte.files;
        for(let i = 0;i < files.length;i++){
            readFile(files[i]);
        }

        console.log(speisekarten[0]);
        console.log(speisekarten);

What can I do that "speisekarten" is an array having the base64-Strings contained before the ajax-request? Or simply: What can I do that console.log(speisekarten[0]); displays the base64-String and not "undefined".


    
         function readFileAsync(file) {
             return new Promise((resolve, reject) => {
               let reader = new FileReader();
          
               reader.onload = () => {
                 resolve(reader.result);
               };
          
               reader.onerror = reject;
         
               reader.readAsDataURL(file);
             })
           }
          
           async function processFile(file) {
             try {
               let content = await readFileAsync(file);
                 speisekarten.push(content);
             } catch(err) {
               console.log(err);
            }
           }

I tried using Promise and callbacks but it didn't work or I did something wrong.

 function add(){
             speisekarten.push(result);
         }
        let speisekarten = [];
        let result;
    
        function readFile(file, myCallback){
            let fr = new FileReader();
    
            fr.onload = function(){
                result = fr.result;

                myCallback(result);
            };
            fr.readAsDataURL(file);
            return; 
        }
        
        let files = speisekarte.files;
        
        if(!files.length) return;
        for(let i = 0;i < files.length;i++){
            readFile(files[i], add);
        }
    }
Tom
  • 1
  • All your examples appear to be mutating `speisekarten` inside asynchronous functions and (in the first example) logging the result before the asynchronous functions have been called or (in the other examples) omitting the code that reads `speisekarten` from the examples but probably doing the same thing. – Quentin Oct 25 '22 at 20:58

0 Answers0