From 95a1b35c917f964d0419e8105954c09ab22e4aaf Mon Sep 17 00:00:00 2001 From: ergunsh Date: Fri, 10 Sep 2021 15:18:14 +0200 Subject: [PATCH] Update `encodedWith` to contain resolved values We already await the promises that we set on the `encodedWith` instead of setting already resolved promises to `encodedWith` we can set the resolved values So, the users can use like `const { mozjpeg: { binary } } = await image.encode({ mozjpeg })` or they can first run `await image.encode({ mozjpeg })` and then `image.encodedWith.mozjpeg.binary` --- libsquoosh/src/index.ts | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/libsquoosh/src/index.ts b/libsquoosh/src/index.ts index 04792394..8ed7e01b 100644 --- a/libsquoosh/src/index.ts +++ b/libsquoosh/src/index.ts @@ -186,7 +186,7 @@ class Image { public file: ArrayBuffer | ArrayLike; public workerPool: WorkerPool; public decoded: Promise<{ bitmap: ImageData }>; - public encodedWith: { [key in EncoderKey]?: Promise }; + public encodedWith: { [key in EncoderKey]?: EncodeResult }; constructor( workerPool: WorkerPool, @@ -227,7 +227,7 @@ class Image { /** * Define one or several encoders to use on the image. * @param {object} encodeOptions - An object with encoders to use, and their settings. - * @returns {Promise} - A promise that resolves when the image has been encoded with all the specified encoders. + * @returns {Promise<{ [key in keyof T]: EncodeResult }>} - A promise that resolves when the image has been encoded with all the specified encoders. */ async encode( encodeOptions: { @@ -236,6 +236,7 @@ class Image { } & T, ): Promise<{ [key in keyof T]: EncodeResult }> { const { bitmap } = await this.decoded; + const setEncodedWithPromises = []; for (const [name, options] of Object.entries(encodeOptions)) { if (!Object.keys(encoders).includes(name)) { continue; @@ -246,18 +247,25 @@ class Image { typeof options === 'string' ? options : Object.assign({}, encRef.defaultEncoderOptions, options); - this.encodedWith[encName] = this.workerPool.dispatchJob({ - operation: 'encode', - bitmap, - encName, - encConfig, - optimizerButteraugliTarget: Number( - encodeOptions.optimizerButteraugliTarget ?? 1.4, - ), - maxOptimizerRounds: Number(encodeOptions.maxOptimizerRounds ?? 6), - }); + setEncodedWithPromises.push( + this.workerPool + .dispatchJob({ + operation: 'encode', + bitmap, + encName, + encConfig, + optimizerButteraugliTarget: Number( + encodeOptions.optimizerButteraugliTarget ?? 1.4, + ), + maxOptimizerRounds: Number(encodeOptions.maxOptimizerRounds ?? 6), + }) + .then((encodeResult) => { + this.encodedWith[encName] = encodeResult; + }), + ); } - await Promise.all(Object.values(this.encodedWith)); + + await Promise.all(setEncodedWithPromises); return this.encodedWith as { [key in keyof T]: EncodeResult }; } }