【问题标题】:Node.js - Async.js map function only showing results of the last iteration?Node.js - Async.js 映射函数只显示最后一次迭代的结果?
【发布时间】:2015-03-25 00:53:55
【问题描述】:

抱歉标题,但我想不出更简单的说法。

我正在尝试使用带有 Node.js 的 async 库来运行 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 模块在每个ticker api 上调用http 请求。返回结果(有些转换)。

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

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

【问题讨论】:

  • 是的,xchange 很可能与它有关。请向我们展示该代码。

标签: javascript node.js async.js


【解决方案1】:

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

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

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

【讨论】:

【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多