Created
October 5, 2012 02:50
-
-
Save dewd/3837794 to your computer and use it in GitHub Desktop.
example of synchronizing through a recursion & async call in node-sync
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// remote API call | |
function asyncFunction2(x,callback ) { | |
var request = require('request'); | |
var url = 'http://www.google.com'; | |
request(url, function (error, response, body) { | |
if (!error && response.statusCode == 200) { | |
console.log('completing transformation of '+x+'^2 = '+x*x); | |
callback(null, x); | |
} | |
}) | |
} | |
// recursive function | |
function recurse(count) { | |
var c = count; | |
var Sync = require('sync'); | |
console.log('current value in recursive function = '+c); | |
Sync(function() { | |
var result = asyncFunction2.sync(null, c); | |
if (c > 0) { | |
c = recurse(count - 1); | |
} | |
}); | |
return c; | |
} | |
// Run in a fiber | |
var Sync = require('sync'); | |
Sync(function(){ | |
var startvalue = 3; | |
console.log('starting with start value of '+startvalue); | |
var j = recurse(3); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If this works, congratulations. I know, you said repeatedly it's not Node's «preferred style», but we are all here to learn... So I give you one more hint:
Fibers make me nervous. They are a crazy idea and I don't know what are their implications. I personally would never use fibers with Node. Streamline.js does not need fibers, because they convert your synchronous code to asynchronous code by a very deep process known as CPS transform. You don't need to understand CPS. You just mark the callbacks with an underscore and write synchronous code. If you are here to learn, you can study the transformed code (it is somewhat readable for easy cases, but very twisted, because a CPS transform positively turns inside out the code). Streamline.js tries to do what a hard-core Node programmer would do when he has the same problem more or less and with the usual caveats of automatic processes.