1 |
|
2 | /**
|
3 | * This simple example shows how you can use synchronous function that uses Fibers in asynchronous environment
|
4 | */
|
5 |
|
6 | var Sync = require('sync');
|
7 |
|
8 | // Simple synchronous function example
|
9 | var someSyncFunction = function(a, b)
|
10 | {
|
11 | // It uses yield!
|
12 | var fiber = Fiber.current;
|
13 |
|
14 | setTimeout(function(){
|
15 | fiber.run(a + b);
|
16 | }, 1000);
|
17 |
|
18 | return yield();
|
19 |
|
20 | }.async() // <-- ATTENTION: here we make this function asynchronous
|
21 |
|
22 | // Here, in regular asynchronous environment we just call this function normally
|
23 | someSyncFunction(2, 3, function(err, result){
|
24 | console.log(result); // will print '5' after 1 sec
|
25 | })
|
26 |
|
27 | // It also may throw and exception
|
28 | var someSyncFunctionThrowingException = function() {
|
29 | throw 'something went wrong';
|
30 | }.async()
|
31 |
|
32 | // Here, in regular asynchronous environment we just call this function normally
|
33 | someSyncFunctionThrowingException(function(err){
|
34 | console.log(err); // will print 'something went wrong'
|
35 | })
|
36 |
|
37 | // If we try to call this function without callback, it will throw an error
|
38 | try {
|
39 | var result = someSyncFunction(2, 3);
|
40 | }
|
41 | catch (e) {
|
42 | console.log(e); // 'Missing callback as last argument to async function'
|
43 | }
|
44 |
|
45 | // But if we call this function from within synchronous environment (inside of a Fiber), it will run!
|
46 | Sync(function(){
|
47 | var result = someSyncFunction(2, 3);
|
48 | console.log(result); // will print '5' after 1 sec
|
49 | }) |
\ | No newline at end of file |