Node.js - Async.js 地图函数只显示最后一次迭代的结果?

Node.js - Async.js map function only showing results of the last iteration?

对不起这个标题,但我想不出更简单的表达方式。

我正在尝试将 async 库与 Node.js 到 运行 3 个异步函数一起使用,并对所有 3 个函数的结果进行一些操作。据我了解, map() 函数允许我 运行 所有 3 并将参数应用于迭代器,然后提供回调以对所有 3 个异步函数(存储在数组中)的结果进行操作。

结果显示 3 个成功响应,但它们都包含来自最后一个(第 3 个)函数的数据 运行,其他 2 个由于某种原因被覆盖。

例如,

/**map the array of exchange names through the iterator function
 * xchange is an external library which has functions of the form -
 * xchange.bitstamp.ticker(callback), xchange.bitfinex.ticker(callback), etc..
 */
var xchange = require("xchange.js"),
    async = require("async");

async.map([ "bitfinex", "bitstamp", "okcoin" ], 
function(item, callback) {
    xchange[item].ticker(function(err, body) {
        console.log("item: " + item);
        console.log(body);

        return callback(err, body);
    });
}, function(err, results) {
    console.log(results);
});


//print out
item: bitstamp
{ bid: 275.16,
  ask: 275.21,
  low: 245,
  high: 309.9,
  volume: 54017.1092978,
  timestamp: 1422283998 }
item: okcoin
{ bid: 279.25,
  ask: 280.44,
  low: 242.93,
  high: 310.57,
  volume: 29342.543,
  timestamp: 1422284015 }
item: bitfinex
{ bid: 279.2,
  ask: 279.77,
  low: 246.59,
  high: 315,
  volume: 165380.17021898,
  timestamp: 1422284011.1361156 }

//Why are these all from the last run?  Should be the results of all 3 above
[ { bid: 279.2,
    ask: 279.77,
    low: 246.59,
    high: 315,
    volume: 165380.17021898,
    timestamp: 1422284011.1361156 },
  { bid: 279.2,
    ask: 279.77,
    low: 246.59,
    high: 315,
    volume: 165380.17021898,
    timestamp: 1422284011.1361156 },
  { bid: 279.2,
    ask: 279.77,
    low: 246.59,
    high: 315,
    volume: 165380.17021898,
    timestamp: 1422284011.1361156 } ]

基本上,xchange ticker 函数使用 request 模块在每个代码 api 上调用 http 请求。返回结果(有些转换)。

我能够 运行 the following code 没有错误,所以我确定它与我的 xchange 库代码有关。

关于可能导致此问题的任何提示或想法?

我遇到了类似的问题,异步映射似乎将结果重写为相同。结果我发现这不是异步问题,而是我的函数 returning 的问题。

我的问题是我将一个对象传递给结果,并传递同一个对象,但每次都更改其中的值。这最终意味着我有一个数组,其中包含对单个对象的多个引用。因此,当我检查我的结果数组时,它看起来好像对最后一个对象进行了多次 return 编辑,而实际上我只对一个对象进行了多次 return 编辑,并在每个循环中更改了其中的值.我怀疑你有同样的问题。

如果您在您的库中创建了一个对象,我们称它为比特币,然后您 return 在第一个映射循环中创建该对象,然后您使用相同的比特币对象并更改其中的值 return 在第二个 map 循环中,那么每个对该对象的引用的值也将被更新,这意味着第一个结果现在看起来像你的第二个结果。

正如您在响应中链接的那样,在 callback 中引用同一个对象,使 map 函数在每次迭代中覆盖该对象,这使得最终结果成为相同的对象,特别是最后一次迭代。