Make angular.forEach wait for promise after going to next object

Before ES2017 and async/await (see below for an option in ES2017), you can’t use .forEach() if you want to wait for a promise because promises are not blocking. Javascript and promises just don’t work that way. You can chain multiple promises and make the promise infrastructure sequence them. You can iterate manually and advance the … Read more

Starting a new thread in a foreach loop

This is because you’re closing over a variable in the wrong scope. The solution here is to use a temporary in your foreach loop: foreach(MyClass myObj in myList) { MyClass tmp = myObj; // Make temporary Thread myThread = new Thread(() => this.MyMethod(tmp)); myThread.Start(); } For details, I recommend reading Eric Lippert’s post on this … Read more

For-each vs Iterator. Which will be the better option

for-each is syntactic sugar for using iterators (approach 2). You might need to use iterators if you need to modify collection in your loop. First approach will throw exception. for (String i : list) { System.out.println(i); list.remove(i); // throws exception } Iterator it=list.iterator(); while (it.hasNext()){ System.out.println(it.next()); it.remove(); // valid here }

Why is “forEach not a function” for this object?

Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this: Object.keys(a).forEach(function (key){ console.log(a[key]); }); Usage note: For an object v = {“cat”:”large”, “dog”: “small”, “bird”: “tiny”};, Object.keys(v) gives you an array of the keys so … Read more