我无法掌握如何获得正确的值。解决我的问题。
例如,我有时会得到不包含两个相同的人的客户列表。然后,对于每个人,我想添加另一个 promise ,其中我传递每个人的名字。问题是有时我得到两个名为“Foo”和“Foo”,而不是“Foo”和“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
}
(...)
最佳答案
如果在程序执行时clients
的值发生变化,则可能是您的问题。由于 for in
循环正在引用键而不是值,并且由于 Promise 链,clients[client]
在稍后的时间点进行评估。
您有两个选择:切换到 for of
循环来获取对象的值而不是键,或者添加 const value =clients[client]
在循环体内并在闭包中使用 value
。这两种方法都会在循环执行时检索值,这正是您想要的。
关于javascript - JS for item in items -> promise 链得到错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60508992/