Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda