samedi 2 juillet 2016

Javascript function with loops and if statements doesn't return the object

I'm probably doing everything wrong, but i've got this function and i can't figure out how to make it work. I've tried different ways, this is the latest one and it doesn't work at all.

function get_price(coin, cb) {
  var result = {}
  get_exchange(coin, function(exch) {
  //get_exchange returns an array like this: ['bittrex','poloniex']
    for (i of exch) {
      get_ticker(i, coin, function(body) {
      //get_ticker returns an object with price data, which i'd like to
      //put in the result object
        if (i == "poloniex") {
          result[i] = body["BTC_" + coin]
          if (Object.keys(result).length == exch.length) {
            cb(result)
          }
        } else {
          result[i] = body
        }
      })
    }
  })
}

var coin = "dcr"
coin = coin.toUpperCase()


get_price(coin, function(body){
  console.log(body)
})

What i'd like to do is to callback the result object when it's like this:

{
poloniex : {bid:"xxxx", last:"xxxx", ask:"xxxx"},
bittrex : {bid:"xxxx", last:"xxxx", ask:"xxxx"}
}

Aucun commentaire:

Enregistrer un commentaire