下划线 _.each 和承诺

underscore _.each and promise

这可能是一个经典问题,但我很难找到合适的答案。

var total_debit = {}; 
_.each(somearray, function(x) {
    if(!total_credit[b.currency]) {
          total_credit[b.currency] = 0;
    }
    // total_debit["usd"] HAS BEEN INITIALIZED!
    total_debit["usd"] += x
});

_.each(total_debit, function(td) {
    // do some stuff
});

问题是第二个 _.each 没有迭代,考虑到 total_debit 仍然是空的。

我尝试使用 Promise,但我可能以错误的方式实现它,导致它无法正常工作。

如果有人能引导我以正确的方式为这个特定的用例实现 Promise,我将永远感激不已。

The problem is that the second _.each is not iterating, considerating total_debit is still empty.

该数组中确实没有任何内容。它的 length 仍然是零。唯一的问题是它现在有一个 .usd 属性(从 somearray 累积了 x)。
问题是你在这里abusing arrays。 Underscore 检测到您正在使用数组,并尝试对其进行迭代(遍历从 0.length 的所有整数键)。但是没有这样的属性。 只需使用对象 (var total_debit = {};),下划线会将其视为 "map" 类型的集合,枚举所有键,包括 .usd.

I tried to use a Promise but I probably implemented it the wrong way cause it's not working.

绝对没有理由在这里使用承诺。您的代码中没有任何内容(至少在您显示的部分中)是异步的。