UNPKG

1.7 kBJavaScriptView Raw
1
2/**
3 * This example shows how we can use Fibers in a single peaces of code,
4 * without wrapping whole application to it
5 *
6 * look at examples/simple.js to see the difference in someAsyncFunction
7 */
8
9var Sync = require('sync');
10
11// Simple asynchronous function with fiber inside example
12function someAsyncFunction(file, callback) {
13 // Here we just wrap the function body to make it synchronous inside
14 // Sync will execute first argument 'fn' in synchronous way
15 // and call second argument 'callback' when function returns
16 // it also calls callback if exception will be thrown inside of 'fn'
17 Sync(function(){
18 var source = require('fs').readFile.sync(null, __filename);
19 return source;
20 }, callback)
21}
22
23// Here we call someAsyncFunction in a normal asynchronous way
24someAsyncFunction(__filename, function(err, source){
25 if (err) return console.error(err);
26 console.log(String(source)); // prints the sources of __filename
27})
28
29// Another example is synchronous function which can be called only inside of a fiber
30// Here we need to turn someSyncFunction to asynchronous one, to call it outside of a Fiber
31// note that .async() method receives 'this' context as first argument and returns new async function instance
32// also if someSyncFunction will throw an exception it will trap into a callback as first argument
33var someSyncFunction = function(file) {
34 var source = require('fs').readFile.sync(null, __filename);
35 return source;
36}.async() // <-- look here
37
38// call it in asynchronous way
39someSyncFunction(__filename, function(err, source){
40 if (err) return console.error(err);
41 console.log(String(source)); // prints the sources of __filename
42})
\No newline at end of file