Skip to content

Instantly share code, notes, and snippets.

@goldalworming
Last active August 29, 2015 14:02
Show Gist options
  • Save goldalworming/ef3d9906e8a914c7e2aa to your computer and use it in GitHub Desktop.
Save goldalworming/ef3d9906e8a914c7e2aa to your computer and use it in GitHub Desktop.
loop in node.js should use recursive or async (node-async) but if you use total.js framework, async feature already exist and this is the comparation of using non-node.js programmer's loop to better approach
rc.zrange(['cust', '0', '-1'], function(err, data) {
if (err) {
rc.quit();
self.throw500(err);
return;
}
var length = data.length;
if (data.length === 0) {
self.json(result);
return;
}
// Create array
var arr = [];
for (var i = 0; i < length; i++)
arr.push('cust:' + data[i]);
var fn_async = function(item, next) {
rc.hgetall(item, function(err, datacust) {
if (err) {
rc.quit();
self.throw500(err);
return;
}
if (datacust)
datacust.id = data[result.length];
result.push(datacust);
next();
});
};
var fn_complete = function() {
rc.quit();
self.json(result);
};
console.log(1);
// Walk through the array (async)
arr.wait(fn_async, fn_complete);
});
var objrows = [];
rc.zrange(['cust','0','-1'],function(err,data){
if (err){throw err; rc.quit();return;}
dl=data.length;
if(dl&&dl>0){
for (var i = 0,imax = dl; i < imax; i++) {
rc.hgetall('cust:'+data[i],function(err,datacust){
if (err){throw err; rc.quit();return;}
objrows.push(datacust);
showoff();
});
};
}
});
function showoff(){
if(objrows.length==dl){
rc.quit();
self.json(objrows);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment