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

411
Views
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 answers
Answer question

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 Report

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 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!