From 06bd692e5c4a8f66960d3919e7087530b60c20dd Mon Sep 17 00:00:00 2001 From: Liam Murphy <43807659+Liamolucko@users.noreply.github.com> Date: Tue, 26 Jan 2021 23:34:40 +1100 Subject: fix(std/node): Stop callbacks being called twice when callback throws error (#8867) --- std/node/_crypto/randomBytes.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'std/node/_crypto/randomBytes.ts') diff --git a/std/node/_crypto/randomBytes.ts b/std/node/_crypto/randomBytes.ts index 28c7e454e..335c92d68 100644 --- a/std/node/_crypto/randomBytes.ts +++ b/std/node/_crypto/randomBytes.ts @@ -39,8 +39,9 @@ export default function randomBytes( cb?: (err: Error | null, buf?: Buffer) => void, ): Buffer | void { if (typeof cb === "function") { + let err: Error | null = null, bytes: Buffer; try { - cb(null, generateRandomBytes(size)); + bytes = generateRandomBytes(size); } catch (e) { //NodeJS nonsense //If the size is out of range it will throw sync, otherwise throw async @@ -50,9 +51,16 @@ export default function randomBytes( ) { throw e; } else { - cb(e); + err = e; } } + setTimeout(() => { + if (err) { + cb(err); + } else { + cb(null, bytes); + } + }, 0); } else { return generateRandomBytes(size); } -- cgit v1.2.3