【发布时间】: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