Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
Cannot seem to convert function to async correctly

I am attempting to convert the following function to be async in React (using CompressorJS):

const UploadImages = ({ jobInfo, setLoading, getData, accountInfo }) => {
    const [files, setFiles] = useState([]);

    const onDrop = useCallback( uploadedFiles => {
        uploadedFiles.forEach((file) => {
            console.log(file)
            new Compressor(file, {
                quality: 0.5,
                width: 500,
                height: 500,
                resize: "contain",function.
                success(result) {
                    setFiles([...files, result]);
                    console.log(result)
                },
                error(err) {
                    console.log(err.message);
                },
            });
        })
    }, [files]);

    return(<a bunch of stuff here>);
}

When using the snippet above, if uploadedFiles contains more than one file, there becomes an issue with compressing each photo and adding it to the state ([files, setFiles]). Only one of the images will be added and the others will be missed.

I have spent a number hours attempting to rework this function in different ways and the best solution I have come up with so far has been the following:

function compressFile(file) {
    return new Promise((resolve, reject) => {
        new Compressor(file, {
            quality: 0.5,
            width: 500,
            height: 500,
            resize: "contain",function.
            success(result) {
                resolve(result) 
            },
            error(err) {
                console.log(err.message);
                reject(err)
            },
        });
    });
}

function compressFiles(files) {
    return new Promise((resolve, reject) => {
        files.forEach((file) => {
            console.log(file)
            compressFile(file)
                .then(compFile => { 
                    console.log(compFile)
                    setFiles([...files, compFile]);
                })
        })
        resolve()
    })
}

const onDrop = useCallback( async acceptedFiles => {
    message.loading('Compressing Images...');
    compressFiles(acceptedFiles)
}, [files]);

Unfortunately, this still does not work and I was wondering if someone could explain where I am going wrong.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This should help:

const compressFiles = files => Promise.all(
  files.map(file => compressFile(file))
)
  .then(compressedFiles => {
    console.log(compressedFiles);
    setFiles([...files, ...compressedFiles]);
  });
about 4 years ago · Juan Pablo Isaza Report

0

setFiles([...files, compFile]);

Every time this line runs, it is going to create an array starting with what's in files, and adding one new file. This will wipe out any other files that have been created since you started, because the files variable only stores what you started with, not any changes you've made. So you will need to use the function version of setFiles, to make sure you always have the latest version of the state:

setFiles(prev => [...prev, compFile]);

A couple other recommendations. First, i'd suggest that you don't set state multiple times in an async loop. This will result in the files being in an unpredictable order and will cause the component to render each step along the way. Instead, you can wait until all the compression is done, and then set state once at the end. To wait for an array of promises, you can use Promise.all. Secondly, since you've already made compressFile return a promise, you do not need to use the new Promise constructor again in compressFiles. Putting these together i recommend:

function compressFiles(files) {
  const promises = files.map(file => compressFile(file));
  Promise.all(promises).then(compressedFiles => {
    setFiles(prev => [...prev, ...compressedFiles]);
  });
}

Or using async/await:

async function compressFiles(files) {
  const promises = files.map(file => compressFile(file));
  const compressedFiles = await Promise.all(promises);
  setFiles(prev => [...prev, ...compressedFiles]);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!