From a1de9dae008abf24882535d61579961b8da5df55 Mon Sep 17 00:00:00 2001 From: jongleberry Date: Fri, 22 Sep 2023 22:22:10 -0700 Subject: [PATCH] reduce a closure --- __tests__/types.js | 2 +- lib/index.js | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/__tests__/types.js b/__tests__/types.js index 3a50a20..120c71f 100644 --- a/__tests__/types.js +++ b/__tests__/types.js @@ -62,4 +62,4 @@ test('a null value', async () => { const result = await streamToString(render`__1__${promise1}__2__${promise2}__3__`) assert.strictEqual(result, '__1____2____3__') expect(result).toMatchSnapshot() -}) \ No newline at end of file +}) diff --git a/lib/index.js b/lib/index.js index d50a840..874a3d9 100644 --- a/lib/index.js +++ b/lib/index.js @@ -29,13 +29,18 @@ function render (template, ...values) { } } - Promise.resolve(value).then((result) => { - if (!result) return - if (typeof result === 'string') return stream.write(result) - if (result.readableObjectMode) throw new Error('Readable object streams are not supported.') - if (result.readable) return pipe(result) - throw new Error(`Value passed did not return a string or a stream: <${typeof result}>${JSON.stringify(result)}`) - }).catch(onError).finally(next) + Promise.resolve(value) + .then(onPromiseResolve) + .catch(onError) + .finally(next) + } + + function onPromiseResolve (result) { + if (!result) return + if (typeof result === 'string') return stream.write(result) + if (result.readableObjectMode) throw new Error('Readable object streams are not supported.') + if (result.readable) return pipe(result) + throw new Error(`Value passed did not return a string or a stream: <${typeof result}>${JSON.stringify(result)}`) } function pipe (readable) {