1

I am using the node.bittrex.api without a problem. I am going through a loop of records and calling getticker for each record. The getticker call returns the values async which is fine, but I wanted some other data from the record outside of the loop, by which time the loop has run through to the end and my callback only uses the values from the last record in the currencies array, which is as expected.

var currencies = [{code:'btc-eth', fee:0.2},{code:'btc-ltc', fee:0.1},{code:'btc-ada', fee:0.5}];

for (index in currencies) {
    bittrex.getticker({ market: currencies[index].code }, function (data, err) {
        console.log("Currency: " + currencies[index].code);
        console.log("Fee: " + currencies[index].fee);
        console.log("Ticker: " + data);
    });
}

Can this be done WITHOUT pass-through parameters (which I can do, but didn't want to fork the package).

Koush
  • 13
  • 2

1 Answers1

0

You can do this by using an immediate function.

var currencies = [{code:'btc-eth', fee:0.2},{code:'btc-ltc', fee:0.1},{code:'btc-ada', fee:0.5}];

for (index in currencies) {
    (function(idx){
      bittrex.getticker({ market: currencies[idx].code }, function (data, err) {
        console.log("Currency: " + currencies[idx].code);
        console.log("Fee: " + currencies[idx].fee);
        console.log("Ticker: " + data);
      });
    })(index);
}

This can also be written as, for brevity :

var currencies = [{code:'btc-eth', fee:0.2},{code:'btc-ltc', fee:0.1},{code:'btc-ada', fee:0.5}];

for (index in currencies) {
    f(index);
}

function f (idx){
  bittrex.getticker({ market: currencies[idx].code }, function (data, err) {
    console.log("Currency: " + currencies[idx].code);
    console.log("Fee: " + currencies[idx].fee);
    console.log("Ticker: " + data);
   });
  }

In case you are using let supported version of node and avoid IIFE,

for ( let index in currencies)
Malice
  • 1,457
  • 16
  • 32
  • Could you please elaborate on that. Where you have (index), I'm guessing this is what will initiate the call to getticker. But how does this hold the value of index? – Koush Jan 04 '18 at 05:04
  • You are calling the anonymous function with index as arguement , Notice the `(index)` at the end of the function definition. This makes sure your current index is captured as idx in the closure and your call back will use this idx – Malice Jan 04 '18 at 05:07
  • Edited my answer – Malice Jan 04 '18 at 05:10
  • Why wouldn't use just use `let index`? It replaces the need for an IIFE. – jfriend00 Jan 04 '18 at 05:37
  • I tried to provide a generic answer for javascript without support for `let`, updated my answer – Malice Jan 04 '18 at 06:02