I'm looking at using ES5's new Array.forEach(). I believe the callbacks for each item should execute in parallel. I'd like a function to return once all values have processed.
// I'd like to make parent_function return a new array with the changed items.
function parent_function(array_of_things) {
new_array = []
array_of_things.forEach( function(thing) {
new_array.push('New '+thing)
if ( new_array.length === array_of_things.length ) {
// OK we've processed all the items. How do I make parent_function return the completed new_array?
return new_array
}
})
}
I suspect that this may be the wrong approach: because the parent_function may finish before every callback has been fired. In this case, firing a custom event (that's handled by whatever needs the data produced after we've processed all the items) may be the best approach. However I didn't find any mention of that in the MDC docs.
But I'm fairly new to JS and would love some peer review to confirm!
Edit: Looks like forEach() is synchronous after all. I was logging the resulting array afterwards and seeing inconsistent results - sometimes two items, sometimes four, etc, which made me think it was async. If you're reading this and having similar behaviour, I suggest you read this item about issues in Chrome's array logging.