Wednesday, 29 November 2017

Using async package, how do I break out of "forEachSeries"?

Hi all,I'm using the async package in order to iterate over arrays of objects. I'm using a function called "forEachSeries". This might be the same thing as "eachSeries".If you're not familiar with this function, it simply iterates over an array with some code that has a callback function. It's basically a for look that operates over an array. The only problem is, I can't figure out how to break out of the loop if I need to.For example, if "forEachSeries" has only iterated over half the array and I have determined that I need to stop the execution of that function, I can't figure out how to break out of the loop. The only thing I can think of is to set a flag outside the loop, then encapsulate everything inside the loop with a check to see if the flag has been triggered. If I determine that I need to exit the loop, I'll just trigger the flag. Then each iteration will skip the code to execute and simply call the callback function. That seems horrifically inefficient, since I still need to iterate over the rest of the array even if I don't do anything.Is there a better way to do this?Here's an example of what I'm talking about. Let's say that I have an array of letters called "letters" that just contains some letters. I want to output each of them to the console, one by one. After I output my first letter 'c' I'd like to stop. So I've set up a flag called "continue_flag" that is true as long as I want the loop to continue. Once I run into the first 'c', I set the flag to false, but I still iterate through the array anyways without doing anything meaningful.I can't seem to get the code to format properly but it begins below:var async = require("async");var letters = ['a', 'b', 'c', 'd', 'e'];var continue_flag = true;async.forEachSeries(letters, function(letter, callback_function){ if (continue_flag){ //continue_flag is true console.log(letter) if (letter == 'c'){//check to see if the letter is 'c' continue_flag = false } callback_function(); } else {//continue_flag is false callback_function(); } } );Is there a better way to do something like this? Is async.forEachSeries even the best function to be using?Thanks!

Submitted November 30, 2017 at 12:44AM by thenewstampede

No comments:

Post a Comment