11const asyncHooks = require ( 'async_hooks' ) ;
2+ const ExecutionContextResource = require ( './lib/ExecutionContextResource' )
23const { isProduction } = require ( './lib' ) ;
34const { create : createHooks } = require ( './hooks' ) ;
45const { ExecutionContextErrors } = require ( './constants' ) ;
@@ -32,7 +33,7 @@ const createExecutionContext = () => {
3233 createHooks ( executionContextMap )
3334 ) . enable ( ) ;
3435
35- return {
36+ const Context = {
3637
3738 /**
3839 * Creates an execution context for the current asyncId process.
@@ -41,7 +42,7 @@ const createExecutionContext = () => {
4142 * @returns void
4243 */
4344 create : ( initialContext = { } ) => {
44- console . log ( 'Creating execution context : ' , executionContextMap ) ;
45+ console . log ( 'Ceating : ' , executionContextMap ) ;
4546 const asyncId = asyncHooks . executionAsyncId ( ) ;
4647
4748 // Creation is allowed once per execution context
@@ -90,8 +91,25 @@ const createExecutionContext = () => {
9091
9192 // Root context
9293 return context ;
94+ } ,
95+
96+ /**
97+ * Runs a given function within "AsyncResource" context, this will ensure the function executed within a uniq execution context.
98+ * @param {Function } fn - The function to run.
99+ * @param {Object } initialContext - The initial context to expose to the function execution
100+ */
101+ run : ( fn , initialContext ) => {
102+ const resource = new ExecutionContextResource ( ) ;
103+
104+ resource . runInAsyncScope ( ( ) => {
105+ Context . create ( initialContext ) ;
106+
107+ fn ( ) ;
108+ } ) ;
93109 }
94110 } ;
111+
112+ return Context ;
95113}
96114
97115global . ExecutionContext = global . ExecutionContext || createExecutionContext ( ) ;
0 commit comments