1 |
|
2 | /**
|
3 | * This simple example shows how you can easily pass variables across fibers tree
|
4 | * it's very useful when you have concurrent program (http server) which deals with a lot of simultenous requests
|
5 | * and you need to maintain the context (e.g. req, res variables) for each local execution stack
|
6 | * without passing it through function arguments endlessly
|
7 | *
|
8 | * In this example, the tree will be looking like:
|
9 | *
|
10 | * --> Request #1
|
11 | * Fiber #1
|
12 | * someGatewayMethod.future()
|
13 | * Fiber #1.1
|
14 | *
|
15 | * --> Request #2
|
16 | * Fiber #2
|
17 | * someGatewayMethod.future()
|
18 | * Fiber #2.1
|
19 | *
|
20 | * So, this program will output:
|
21 | * request #1
|
22 | * request #2
|
23 | */
|
24 |
|
25 | var Sync = require('sync');
|
26 |
|
27 | var someGatewayMethod = function() {
|
28 |
|
29 | var scope = Sync.scope;
|
30 | setInterval(function(){
|
31 | console.log(scope.req);
|
32 | }, 1000)
|
33 |
|
34 | }.async()
|
35 |
|
36 | // One fiber (e.g. user's http request)
|
37 | Sync(function(){
|
38 |
|
39 | Sync.scope.req = 'request #1';
|
40 |
|
41 | // future() runs someGatewayMethod in a separate "forked" fiber
|
42 | someGatewayMethod.future();
|
43 | })
|
44 |
|
45 | // Another fiber (e.g. user's http request)
|
46 | Sync(function(){
|
47 |
|
48 | Sync.scope.req = 'request #2';
|
49 |
|
50 | // future() runs someGatewayMethod in a separate "forked" fiber
|
51 | someGatewayMethod.future();
|
52 | }) |
\ | No newline at end of file |