Javascript 洛达斯的运营有时无法如期完成
我正在构建一个交易机器人,我有这段代码,它接受5个数组的数组(API一次允许5个价格请求)。对于这些货币中的每一种,都执行API调用并检索带有承诺的结果。在承诺中,我通过返回的每种货币计算平均价格,然后将其保存到MongoDBJavascript 洛达斯的运营有时无法如期完成,javascript,node.js,asynchronous,promise,lodash,Javascript,Node.js,Asynchronous,Promise,Lodash,我正在构建一个交易机器人,我有这段代码,它接受5个数组的数组(API一次允许5个价格请求)。对于这些货币中的每一种,都执行API调用并检索带有承诺的结果。在承诺中,我通过返回的每种货币计算平均价格,然后将其保存到MongoDB Market.prototype.fetchPrices = function(currencyPairs){ var self = this let currencyPairGroups = chunkBy5(currencyPairs) _.forEach
Market.prototype.fetchPrices = function(currencyPairs){
var self = this
let currencyPairGroups = chunkBy5(currencyPairs)
_.forEach(currencyPairGroups, function(currencyPairGroup){
wc.price(currencyPairGroup).then(function(res){
let pairs = Object.keys(res);
_.forEach(pairs, function(pair) {
let currentObj = res[pair]
currentObj.pair = pair
currentObj.mid = _.mean([currentObj.bid, currentObj.ask])
console.log('Before saving ' + '\n' +
'this is the pair ' + currentObj.pair + '\n' +
'and this is the bid ' + currentObj.bid + '\n' +
'and this is the ask ' + currentObj.ask + '\n' +
'and this is the mid ' + currentObj.mid + '\n' +
'is the mid a NaN? ' + isNaN(currentObj.mid) + '\n')
savePrice(currentObj)
self.emit('emitPrice', currentObj)
})
})
})
}
几乎总是这样,这样做效果很好。但是,有时currentObj.mid会被传递为NaN,并且保存到Mongoose的验证会失败。console.log如下所示
this is the pair USD-MXN
and this is the bid 17.90732
and this is the ask 17.91332
and this is the mid NaN
is the mid a NaN? true
我觉得这是一个异步问题,但我认为我的承诺中没有任何东西是异步的。另外,我不知道为什么它几乎每隔一段时间都能工作。甚至不知道该问什么问题来解决这个问题。as
。mid
直接从计算得出。bid
和。ask
-这不太可能是异步问题-什么是。意思是?为什么不直接使用(.ask+.bid)/2
?试试.mean([Number(currentObj.bid),Number(currentObj.ask)])
-不过,你可能会认为lodash会这么做,所以这可能是一个多余的建议-注意:不,lodash似乎并没有对数据进行非常基本的“净化”——也许你的出价和出价结果是错误的(在某些情况下)字符串?