Lodash操作有时无法在Promise中完成

时间:2017-06-17 04:49:31

标签: javascript node.js asynchronous promise lodash

我正在建立一个交易机器人,我有这个代码,它采用5的数组(API允许一次5个价格请求)。对于这些货币中的每一种,this api执行API调用并使用承诺检索结果。在我通过返回的每种货币的承诺中,计算价格的平均值,然后将其保存到MongoDB。

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

我觉得这是一个异步问题,但我不认为我的承诺中的任何内容都是异步的。此外,几乎每隔一段时间都不知道它为什么会起作用。甚至不知道要问什么问题来解决这个问题。

0 个答案:

没有答案