UNPKG

1.95 kBJavaScriptView Raw
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
25var Sync = require('..');
26
27var x = function() {
28
29 //Sync.sleep(100);
30
31 throw new Error('hehe');
32 console.log(scope.req);
33
34}.async();
35
36var someGatewayMethod = function() {
37
38 var scope = Sync.scope;
39
40 //throw new Error('hehe');
41 //Sync.sleep(100);
42
43 //x.future();
44
45 x.future();
46 //x();
47
48 return;
49
50 setTimeout(function(){
51
52 //console.log(Fiber.current)
53 //throw new Error('hehe');
54
55 var x = function() {
56
57 throw new Error('hehe');
58 console.log(scope.req);
59
60 }.async();
61
62 x.future();
63 //x();
64
65
66 }.async(), 100)
67
68
69}.async()
70
71
72// One fiber (e.g. user's http request)
73Sync(function(){
74
75 Sync.scope.req = 'request #1';
76
77 // future() runs someGatewayMethod in a separate "forked" fiber
78 someGatewayMethod.future();
79 //someGatewayMethod();
80
81 //console.log(f.error);
82
83 //someGatewayMethod();
84 //Sync.waitFutures();
85
86}, Sync.log)
87
88// Another fiber (e.g. user's http request)
89/*Sync(function(){
90
91 Sync.scope.req = 'request #2';
92
93 // future() runs someGatewayMethod in a separate "forked" fiber
94 someGatewayMethod.future();
95})*/
\No newline at end of file