Skip to content

Instantly share code, notes, and snippets.

@dewd
Created October 5, 2012 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dewd/3837794 to your computer and use it in GitHub Desktop.
Save dewd/3837794 to your computer and use it in GitHub Desktop.
example of synchronizing through a recursion & async call in node-sync
// 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);
})
@nalply
Copy link

nalply commented Oct 5, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment