Search code examples
javascriptecmascript-6teamspeak

JS for item in items -> promise chain gets wrong values


I can't grasp how to get the correct value. Blow my problem.

So for example i sometimes get the clientlist which does not contain two of the same people ever. Then for each of them i want to add another promise where i pass the name of each. Problem is that sometimes i get two called "Foo" and "Foo", instead of "Foo" and "Bar".

(...)    
for (let client in clients) {

   chain = chain.then(resolve => mainEvent(clients[client])) // since this is built and executed after, I sometimes get repeating client names. It's really unpredictable and weird.

   ev.client.chat(clients[client].name()) // correct output but this is in sync with the loop
}
(...)

Solution

  • If the values of clients change while your program is executing, that could be your problem. Since the for in loop is making a reference to the keys but not the values, and clients[client] is evaluated at a later point in time because of the promise chain.

    You have two options: either switch to a for of loop to get the values of the object instead of the keys, or add a const value = clients[client] inside the body of the loop and use value in your closures. Both of these methods will retrieve the values at the time of the loop's execution, which is what you want.