Is there a better way to do this in node.js?

I'm using node.js to make a call to redis to grab some data. The data then needs to be sorted to arrays - not a costly procedure but I need a function to execute asynchronously right after the sorting is done.

If I write the function right after the sorting code, it will fire off before the array sorting stuff is done. So I see a couple of ways of solving this:

1) Write for() loops where the next one starts when the previous one is at its last iteration; At the VERY end, put the asynchronous method to make sure it runs after all the loops are finished.

2) Use setTimeout(). I'm uneasy about doing that because it seems like maybe depending on the size of arrays that need to be processed it might magically fire off too soon, or too late.

Is there a better way to go about this than nesting for loops?

You could use setTimeout() and set the wait time to some function of the size of the array. I sympathize with you though, setTimeout() seems pretty scary. However, it is a necessary evil at times like these.

I surprised what ever code you are using to access Redis doesn't have async capabilities, but this should work:

var done = false;

function sort(){
   ...
   done = true;
}

function sortDone(){
   if(done){
      ...
   }else{
      process.nextTick(sortDone);
   }
}

It looks like you just want reduceRight.

arr.reduceRight( function( p, c, i ) {
    // sort
    if ( i === 0 ) {
        // You know you're at the last iteration
        // so you can call whatever async func you want
    }
});