0

I've tried to solve this the last hours and cannot come to a conclusion. It seems that adding await before sharp(image).rotate(value).toBuffer() in the below code makes it jump over all lines after.

  const promises = this.imagesToProcess.map(async (image) => {
    try {
      await sharp(image).rotate(value).toBuffer() // <-- This line here cause the problem
      console.log(this.terminalColors.green, `${image} [Rotate - Processed]`)  // <-- This line will not run unless 'await' is removed
    } catch (e) {
      console.error(e)
      this.errors.push(this.terminalColors.red, `Could not process file ${image} [Skipping]`)
    }
  })

  // Await all proimises
  Promise.all(promises)

I'm 100% sure this is due to me not understanding asynchronous programming all too well. I just can't figure it out, however.

It's worth mentioning that "sharp" is a image manipulation library for NodeJS. The toBuffer() function seems to return a promise, according to the index.d.ts file:

/**
 * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported.
 * By default, the format will match the input image, except SVG input which becomes PNG output.
 * @param options resolve options
 * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data.
 * @returns A promise that resolves with the Buffer data.
 */
toBuffer(options?: { resolveWithObject: false }): Promise<Buffer>;
TheWilley
  • 29
  • 1
  • 5

1 Answers1

1

Your promises are not returning the buffers, which is what I think you want to do. Try:

  const promises = this.imagesToProcess.map(async (image) => {
    try {
      const buffer = await sharp(image).rotate(value).toBuffer() // <-- store return in variable
      console.log(this.terminalColors.green, `${image} [Rotate - Processed]`)
      return buffer // <----------- return the buffer
    } catch (e) {
      console.error(e)
      this.errors.push(this.terminalColors.red, `Could not process file ${image} [Skipping]`)
    }
  })
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34