UNPKG

1.12 kBJavaScriptView Raw
1
2/**
3 * This simple example shows how you can run ANY asynchronous function in synchronous manner
4 */
5
6var Sync = require('sync');
7
8// Simple asynchronous function example
9function someAsyncFunction(a, b, callback) {
10 setTimeout(function(){
11 callback(null, a + b);
12 }, 1000)
13}
14
15// Here we need to start new Fiber inside of which we can do our tests
16Sync(function(){
17
18 // Here we just need to call the method .sync() for synchronous behavior
19 // (first argument to sync is an object context, we don't need it in this case)
20 // the 'result' variable will be assigned only after function will return value
21 var result = someAsyncFunction.sync(null, 2, 3);
22 console.log(result); // 5
23
24 // Note: thanks to pthreads, other code of the process can
25 // be executed normally while we are waiting for result of someAsyncFunction
26 // for example, fs.readFileSync blocks whole process, but with .sync() method we only block current thread:
27 var source = require('fs').readFile.sync(null, __filename);
28 console.log(String(source)); // prints the source of this example itself
29
30})
\No newline at end of file