1 |
|
2 | /**
|
3 | * Future example
|
4 | * Shows how we can postpone yielding and call multiple functions in parallel
|
5 | * And then wait for all results in a single point
|
6 | *
|
7 | */
|
8 |
|
9 | var Sync = require('sync');
|
10 |
|
11 | // Simple asynchronous function example
|
12 | function someAsyncFunction(a, b, callback) {
|
13 | setTimeout(function(){
|
14 | callback(null, a + b);
|
15 | }, 1000)
|
16 | }
|
17 |
|
18 | // Here we need to start new Fiber inside of which we can do our tests
|
19 | Sync(function(){
|
20 |
|
21 | // no-yield here, call asynchronously
|
22 | // this functions executes in parallel
|
23 | var foo = someAsyncFunction.future(null, 2, 3);
|
24 | var bar = someAsyncFunction.future(null, 4, 4);
|
25 |
|
26 | // we are immediately here, no blocking
|
27 |
|
28 | // foo, bar - our tickets to the future!
|
29 | console.log(foo); // { [Function: Future] result: [Getter], error: [Getter] }
|
30 |
|
31 | // Yield here
|
32 | console.log(foo.result, bar.result); // '5 8' after 1 sec (not two)
|
33 |
|
34 | // Or you can straightly use Sync.Future without wrapper
|
35 | // This call doesn't blocks
|
36 | someAsyncFunction(2, 3, foo = new Sync.Future());
|
37 |
|
38 | // foo is a ticket
|
39 | console.log(foo); // { [Function: Future] result: [Getter], error: [Getter] }
|
40 |
|
41 | // Wait for the result
|
42 | console.log(foo.result); // 5 after 1 sec
|
43 |
|
44 | /**
|
45 | * Timeouts
|
46 | */
|
47 |
|
48 | // someAsyncFunction returns the result after 1000 ms
|
49 | var foo = someAsyncFunction.future(null, 2, 3);
|
50 | // but we can wait only 500ms!
|
51 | foo.timeout = 500;
|
52 |
|
53 | try {
|
54 | var result = foo.result;
|
55 | }
|
56 | catch (e) {
|
57 | console.error(e.stack); // Future function timed out at 500 ms
|
58 | }
|
59 |
|
60 | // Same example with straight future function
|
61 | someAsyncFunction(2, 3, foo = new Sync.Future(500));
|
62 |
|
63 | try {
|
64 | var result = foo.result;
|
65 | }
|
66 | catch (e) {
|
67 | console.error(e.stack); // Future function timed out at 500 ms
|
68 | }
|
69 | }) |
\ | No newline at end of file |