From 3cfbc7f9d2662e62236c42b6abd7ad2fa750a6ec Mon Sep 17 00:00:00 2001 From: Zachary Wade Date: Tue, 1 Feb 2022 20:49:54 -0500 Subject: [PATCH] Have promiseCallback make callbacks and promises behave the same --- lib/utilities.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/utilities.js b/lib/utilities.js index b9bd3e7..4f16602 100644 --- a/lib/utilities.js +++ b/lib/utilities.js @@ -50,10 +50,19 @@ const errorFunc = (resolve, reject) => isFunc(reject) ? reject : resolve; /** * Return a callback function for promise resole/reject args. + * Ensures that callback is called only once. * @returns {Function} */ const promiseCallback = (resolve, reject) => { - return err => err ? errorFunc(resolve, reject)(err) : resolve(); + let hasFired = false; + return (err) => { + if (hasFired) { + return; + } + + hasFired = true; + return err ? errorFunc(resolve, reject)(err) : resolve(); + }; }; /** @@ -177,8 +186,9 @@ const saveBufferToFile = (buffer, filePath, callback) => { }; // Setup file system writable stream. let fstream = fs.createWriteStream(filePath); - fstream.on('error', err => callback(err)); - fstream.on('close', () => callback()); + console.log("Calling saveBuffer"); + fstream.on('error', err => (console.log("err cb"), callback(err))); + fstream.on('close', () => (console.log("close cb"), callback())); // Copy file via piping streams. readStream.pipe(fstream); };