0

I don't want to have to npm anything. I'm just trying to create a script to process a few files but as I have to use streams to process the files I need to use some form of async forEach.

The issue is I just want a simple .js file I can run, I don't want to have to npm install a bunch of stuff.

Justin808
  • 20,859
  • 46
  • 160
  • 265
  • Would this be an acceptable answer:http://stackoverflow.com/questions/4631774/coordinating-parallel-execution-in-node-js/4631909#4631909 ? – slebetman Sep 09 '15 at 09:00

1 Answers1

2

If you want, for example, the forEach functionality of async (https://github.com/caolan/async), you can always look into its' source and reimplement it yourself.

A simplistic implementation could look like this:

function forEach(arr, fun, callback) {
    var toDo = arr.length;
    var doneCallback = function() {
        --toDo;
        if(toDo === 0) {
            callback();
        }
    }

    for(var i = 0, len = arr.length; i < len; ++i) {
        fun(arr[i], doneCallback);
    }
}

It assumes the function you want to run takes an array element and a callback. You could modify it to collect results, handle errors, etc. I encourage you to look into async's source.

ralh
  • 2,514
  • 1
  • 13
  • 19
  • @Justin808 - this won't perform a parallel forEach as you're expecting. This simply loops over the array and calls a function in a serial manner. To make this truly async, the function call inside the for loop should become: `setImmediate(fun, [arr[i], doneCallback]);` – Brandon Smith Sep 09 '15 at 12:09
  • Of course, for it to be asynchronous, the function itself has to be asynchronous. You probably mean that the loop itself is not asynchronous, but that doesn't really make sense. Why would it? node.js is single threaded, it doesn't speed up anything. Assuming, again, that `fun` is asynchronous and does not block for more than a moment. I think the OP wanted something to handle existing functions being asynchronous, not to actually leverage asynchrony in any way. – ralh Sep 09 '15 at 12:13