UNPKG

1.06 kBJavaScriptView Raw
1
2/**
3 * Example demonstrates how you can use Function.prototype.async() to use any
4 * prototype function synchronously - transparently binded current object to it
5 */
6
7var Sync = require('sync');
8
9// Simple asynchronous function
10function asyncFunction(a, b, callback) {
11 process.nextTick(function(){
12 callback(null, a + b);
13 })
14}
15
16// Example class with assigned value
17function SomeClass(a) {
18 this.a = a;
19}
20
21// Define prototype method in this class, which is synchronous inside
22// just turn it to regular asynchronous function using Function.prototype.async()
23// if we lack the first argument (context) it will transparently pass current object
24// from which the function will be called
25SomeClass.prototype.method = function(b) {
26 return asyncFunction.sync(null, this.a, b);
27}.async() // <-- look here
28
29// Create instance passing 'a' value as argument
30var obj = new SomeClass(2);
31
32// Call our "synchronous" method asynchronously, passing second parameter 'b'
33obj.method(3, function(err, result){
34 console.log(result); // will print '5'
35});
\No newline at end of file