22
33` node-simple-context ` is an helper to create a context in node.
44
5+ This library is highly inspired by [ nctx] ( https://github.com/devthejo/nctx ) .
6+
57## Installation
68
79``` sh
@@ -40,39 +42,43 @@ console.log(contextA.get('xxx')); // undefined
4042
4143### Complex
4244
45+ #### With [ ` async_hooks ` ] ( https://nodejs.org/api/async_hooks.html )
46+
4347``` ts
4448const context = createSimpleContext ();
4549
46- const func = (forkId : string ): string => {
47- const foo = context .getForkProperty (forkId , ' foo' );
50+ const func = (): string => {
51+ const foo = context .getForkProperty (' foo' );
4852 return ` foo=${foo } ` ;
4953};
5054
51- context .fork (' X ' );
52- context .setForkProperty (' X ' , ' foo' , ' bar' );
55+ context .fork ();
56+ context .setForkProperty (' foo' , ' bar' );
5357
5458const res = await Promise .all ([
5559 new Promise ((resolve ) => {
56- context . fork ( ' A ' );
57- context .setForkProperty ( ' A ' , ' foo ' , ' tata ' ),
58- setTimeout (() => {
59- resolve (func (' A ' ));
60- }, 400 );
60+ setTimeout (() => {
61+ context .fork ();
62+ context . setForkProperty ( ' foo ' , ' tata ' );
63+ resolve (func ());
64+ }, 400 );
6165 }),
62- func (' X ' ),
66+ func (),
6367 new Promise ((resolve ) => {
64- context . fork ( ' B ' );
65- context .setForkProperty ( ' B ' , ' foo ' , ' toto ' ),
66- setTimeout (() => {
67- resolve (func (' B ' ));
68- }, 200 );
68+ setTimeout (() => {
69+ context .fork ();
70+ context . setForkProperty ( ' foo ' , ' toto ' );
71+ resolve (func ());
72+ }, 200 );
6973 }),
7074]);
7175
7276console .log (res ); // ['foo=tata', 'foo=bar', 'foo=toto']
7377```
7478
75- To achieve this, you can also define multiple contexts in the same file, like that:
79+ #### Without [ ` async_hooks ` ] ( https://nodejs.org/api/async_hooks.html )
80+
81+ Here, I define multiple contexts in the same file, like that:
7682
7783``` ts
7884const contextA = createSimpleContext ();
@@ -88,21 +94,19 @@ contextC.setProperty('foo', 'bar');
8894
8995const res = await Promise .all ([
9096 new Promise ((resolve ) => {
91- contextA . setProperty ( ' foo ' , ' tata ' ),
92- setTimeout (() => {
93- resolve (func (contextA ));
94- }, 400 );
97+ setTimeout (() => {
98+ contextA . setProperty ( ' foo ' , ' tata ' );
99+ resolve (func (contextA ));
100+ }, 400 );
95101 }),
96102 func (contextC ),
97103 new Promise ((resolve ) => {
98- contextB . setProperty ( ' foo ' , ' toto ' ),
99- setTimeout (() => {
100- resolve (func (contextB ));
101- }, 200 );
104+ setTimeout (() => {
105+ contextB . setProperty ( ' foo ' , ' toto ' );
106+ resolve (func (contextB ));
107+ }, 200 );
102108 }),
103109]);
104110
105111console .log (res ); // ['foo=tata', 'foo=bar', 'foo=toto']
106112```
107-
108- :warning : Otherwise, I advice you to use [ nctx] ( https://github.com/devthejo/nctx ) which uses ` async_hooks ` to detect dynamically the context in asynchronous call.
0 commit comments