From 487833a6e73f371525015844ed1382ebb1d19a29 Mon Sep 17 00:00:00 2001 From: Ayoub-Mabrouk Date: Sat, 9 Nov 2024 00:08:51 +0100 Subject: [PATCH] Refactor wrap function for better readability and efficiency - Removed unnecessary es initialization outside the condition. - Simplified the flow by checking syncHooks.AsyncResource and unInAsyncScope in a more direct manner. - Enhanced clarity by removing redundant comments and streamlining the code structure. - Maintained the backporting of the AsyncResource.bind static method for compatibility. --- index.js | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index e68df7b..546ace3 100644 --- a/index.js +++ b/index.js @@ -213,22 +213,18 @@ function tryRequireAsyncHooks () { /** * Wrap function with async resource, if possible. * AsyncResource.bind static method backported. + * + * @param {Function} fn + * @returns {Function} * @private */ function wrap (fn) { - var res - - // create anonymous resource if (asyncHooks.AsyncResource) { - res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') - } - - // incompatible node.js - if (!res || !res.runInAsyncScope) { - return fn + var res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn') + if (res.runInAsyncScope) { + return res.runInAsyncScope.bind(res, fn, null) + } } - - // return bound function - return res.runInAsyncScope.bind(res, fn, null) + return fn }