I’m using UnderscoreJs with nodejs and have a need for the _.times() method. times() will invoke a function X number of times
This works as expected, however I need to iterate in a series, instead of in parallel which this appears to be doing.
Any idea if there’s a way to use this in series w/ callback methods?
Given something like this:
Then the three
fcalls will happen in series but thesome_async_callcalls won’t necessarily happen in series because they’re asynchronous.If you want to force your calls to run in series then you need to use the callback on the async call to launch the next one in the series:
That approach will execute the three
some_async_callsin series but, alas, the initialf(3)will return immediately. One solution to that problem is, of course, another callback:Where does
_.timesin with all this? No where really._.timesis just aforloop:_.timesexists for completeness and to allow you to addforloop when using_.chain. You could probably shoe-horn it in if you really wanted to but you would be making a big ugly mess instead of simplifying your code.You could use 250R’s async idea but you’d have to build an array of three functions but
_.rangeand_.mapwould be more appropriate for that than_.times:But you still have to modify
fto have a callback function and if you’re always callingfthree times then:might be better than dynamically building the array with
_.rangeand_.map.The real lesson here is that once you get into asynchronous function calls, you end up implementing all your logic as callbacks calling callbacks calling callbacks, callbacks all the way down.