1
\$\begingroup\$

I Have the below code that gets urls of PDF files, send them to a convert function and returns them as images, is there a way to make this code more readable?

Is there a way to avoid functions chaining?

import PDFtoImages from '../PDFtoImages'
    
export async function convertPDF(file, category) {
const images= await PDFtoImages(file.data)
return {
   category: category ? [category] : [],
    images
  }
}
    
export function fetchBlob(url, opts = {}) {
  return fetch(url, opts).then(res => {
    if (!res.ok) return Promise.reject(new Error(res.statusText))
      return res.blob()
    })
}

export async function fetchFilesAsImages(filesUrls) { 
  const pdfAsImages= []
  await Promise.all(
    filesUrls.map(async file=> {
      pdfAsImages.push(
        await convertPDF(
          {data: await fetchBlob(file.url)},
          file.category
        )
      )
    })
  )
  return pdfAsImages
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I changed the title so that it describes what the code does per site goals: "State what your code does in your title, not your main concerns about it.". Feel free to edit and give it a different title if there is something more appropriate. I also moved the text from the title into the body as a question- does that look okay? \$\endgroup\$ Commented Jan 20, 2021 at 22:03
  • 1
    \$\begingroup\$ Does the code in the code block reflect the actual indentation, or did you just indent the outer most statements (e.g. import..., export...., } so they would be pre-formatted? For more information about code blocks see the editing help page \$\endgroup\$ Commented Jan 21, 2021 at 0:17

1 Answer 1

2
\$\begingroup\$

The main issue I see with this code is in the fetchFilesAsImages() function. You're needlessly building a results array to return at the end of the call fetchFilesAsImages(). Why not just take advantage of the fact that Promise.all() will already return a list of what each promise resolved to. So, you could instead write fetchFilesAsImages() as follows:

export async function fetchFilesAsImages(filesUrls) {
  return await Promise.all(
    filesUrls.map(async ({ url, category }) => {
      const data = await fetchBlob(url);
      return await convertPDF({ data }, category);
    })
  );
}

One other thing I would suggest is to just use async/await syntax everywhere. Your fetchBlob() could look a little cleaner with it:

export async function fetchBlob(url, opts = {}) {
  const res = await fetch(url, opts);
  if (!res.ok) throw new Error(res.statusText);
  return res.blob();
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.