Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

412
Vistas
initialization in async reduce
  const handleFileChange = async (e) => {
        const target = e?.target?.files;
        const attachments = await Array.from(target).reduce(async (acum, file) => {
            file.id = uniqid();
            // const format = file.name.split('.').pop();
            // if (IMAGE_FORMATS.includes(format)) {
            setIsLoading(true);
            if (file.type.startsWith('image/')) {
                const response = await channel.sendImage(file);
                file.src = response.file;
                acum.images.push(file);
            } else {
                const response = await channel.sendFile(file);
                file.src = response.file;
                acum.files.push(file);
            }
            setIsLoading(false);
            return acum;
        }, Promise.resolve({ files: [], images: [] }));
        setFilesList(prev => {
            console.log('files', [...prev, ...attachments.files]);
            return [...prev, ...attachments.files];
        });
        setImagesList(prev => {
            console.log('images', [...prev, ...attachments.images]);
            return [...prev, ...attachments.images];
        });
    };

In the above code I got the following error enter image description here It looks it's cause by my initialization of array, but how should I address it?

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

An async function returns Promise, which makes it difficult to work with when using .reduce() as you would need to await your accumulator each iteration to get your data. As an alternative, you can create an array of Promises using the mapper function of Array.from() (which you can think of as using .map() directly after Array.from()). The idea here is that the map will trigger multiple asynchronous calls for each file by using sendImage/sendFile. These calls will run in parallel in the background. The value that we return from the mapping function will be a Promise that notifies us when the asynchronous call has successfully completed (once it resolves). Moreover, the mapping function defines what the promise resolves with, in our case that is the new object with the src property:

const isImage = file => file.type.startsWith('image/');
const filePromises = Array.from(target, async file => {
  const response = await (isImage(file) ? channel.sendImage(file) : channel. sendFile(file));
  return {...file, type: file.type, src: response.file};
});

Above filePromises is an array of Promises (as the async mapper function returns a Promise implicitly). We can use Promise.all() to wait for all of our Promises to resolve. This is faster than performing each asynchronous call one by one and only moving to the next once we've waited for the previous to complete:

setIsLoading(true); // set loading to `true` before we start waiting for our asynchronous work to complete
const fileObjects = await Promise.all(filePromises);
setIsLoading(false); // complete asynchronous loading/waiting

Lastly, fileObjects is an array that contains all objects, both files and images. We can do one iteration to partition this array into seperate arrays, one for images, and one for files:

const attachments = {files: [], images: []};
for(const fileObj of fileObjects) {
  if(isImage(fileObj)) 
    attachments.images.push(fileObj);
  else
    attachments.files.push(fileObj);
}
about 4 years ago · Santiago Gelvez Denunciar

0

The reduce is not really necessary at this point:

Here is a solution with a map to transform the elements in promises and then Promise.all to wait for the exectution

const channel = {
 sendImage: async (file) => {return {file}},
 sendFile: async (file) => {return {file}}
 }

const uniqid = () => Math.floor(Math.random() * 100);

const input = {
  target: {
    files: [{
      src: 'src',
      type: 'image/123'
      },
      {
      src: 'src',
      type: 'image/321'
      },
      {
      src: 'src',
      type: '123'
      },
      {
      src: 'src',
      type: '321'
      }]
    }
  }
  
const setIsLoading = () => null;
 

const handleFileChange = async (e) => {
  const target = e?.target?.files;

   setIsLoading(true);
    const attachments = {
      images: [],
      files: [],
    }
        
   await Promise.all(Array.from(target).map((file) => {
      file.id = uniqid();
      return new Promise(async (resolve) => {
        if (file.type.startsWith('image/')) {
            const response = await channel.sendImage(file);
            file.src = response.file;
            attachments.images.push(file);
        } else {
            const response = await channel.sendFile(file);
            file.src = response.file;
            attachments.files.push(file);
        }
        resolve();
      });
    }));
    
  setIsLoading(false)

  return attachments;
};

handleFileChange(input).then(res => console.log(res))
    

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda