1 |
|
2 | /**
|
3 | * This example shows how you can deal with exceptions handling with Sync library
|
4 | */
|
5 |
|
6 | var Sync = require('sync');
|
7 |
|
8 | // Simple asynchronous function which returns and error to a callback
|
9 | // look at examples/simple.js to see how someAsyncFunction works normally
|
10 | function someAsyncFunction(a, b, callback) {
|
11 | setTimeout(function(){
|
12 | callback('something went wrong');
|
13 | }, 1000)
|
14 | }
|
15 |
|
16 | // Here we need to start new Fiber inside of which we can do our tests
|
17 | Sync(function(){
|
18 | try {
|
19 | var result = someAsyncFunction.sync(null, 2, 3);
|
20 | }
|
21 | catch (e) {
|
22 | console.error(e); // will print 'something went wrong' after 1 sec
|
23 | }
|
24 | })
|
25 |
|
26 | /**
|
27 | * Another example shows how Sync throws an exception to a callback
|
28 | * if some error occured inside of 'fn' body
|
29 | * look at examples/fiber.js for more details about Sync
|
30 | */
|
31 |
|
32 | // Simple asynchronous function with fiber inside and throws an exception
|
33 | function someFiberAsyncFunction(file, callback) {
|
34 | Sync(function(){
|
35 | throw new Error('something went wrong again');
|
36 | }, callback)
|
37 | }
|
38 |
|
39 | // Call someAsyncFunction in a normal asynchronous way
|
40 | someFiberAsyncFunction(__filename, function(err, source){
|
41 | if (err) return console.error(err); // will print 'something went wrong again'
|
42 | })
|
43 |
|
44 | // Another example is synchronous function which can be called only inside of a fiber
|
45 | // and throws an exception inside of it's body
|
46 | var someSyncFunction = function(file) {
|
47 | throw new Error('something went wrong synchronously');
|
48 | }.async() // <-- Turn someSyncFunction to asynchronous one
|
49 |
|
50 | // call it in asynchronous way
|
51 | someSyncFunction(__filename, function(err, source){
|
52 | if (err) return console.error(err); // will print 'something went wrong synchronously'
|
53 | })
|
54 |
|
55 | /**
|
56 | * Exceptions inside of a Sync.Parallel
|
57 | * see examples/parallel.js for more details about Sync.Parallel
|
58 | */
|
59 | Sync(function(){
|
60 |
|
61 | // Here we need to call someAsyncFunction two times with different arguments in parallel
|
62 | // but wait for both results and only then continue
|
63 | try {
|
64 | var results = Sync.Parallel(function(callback){
|
65 | someAsyncFunction(2, 2, callback());
|
66 | });
|
67 | }
|
68 | catch (e) {
|
69 | console.error(e); // will print 'something went wrong' after 1 sec
|
70 | }
|
71 | }) |
\ | No newline at end of file |