0

this is my first post. I hope I get everything across to you. I've searched extensively for a solution but I'm not really sure how to describe my problem.

This is a problem I've had numerous times for a few months since starting with JavaScript. Every time I've come across it, I've just coded it another way (always longer).

My problem has always occurred within a for loop when variables I wish to use within a function expression (within the loop) are changing. It's very difficult for me to describe so here's a snippet from my project:

var exportList = [
    ['getmarkets', 'getcurrencies', 'getticker', 'getmarketsummaries',
    'getmarketsummary', 'getorderbook', 'getmarkethistory'],
    ['buylimit', 'selllimit', 'cancel', 'getopenorders'],
    ['getbalances', 'getbalance', 'getdepositaddress', 'withdraw',
    'getorder', 'getorderhistory', 'getwithdrawalhistory', 'getdeposithistory']
];

for (var i1 = 0; i1 < exportList.length; i1++) {
    for (var i2 = 0; i2 < exportList[i1].length; i2++) {

        var ext = exportList[i1][i2];
        var subExt = '';

        if (i1 === 0) subExt = '/public/';
        else if (i1 === 1) subExt = '/market/';
        else if (i1 === 2) subExt = '/account/';

        module.exports[ext] = function (options) {
            options.ext = subExt + ext;
            sendRequest(options);
        }
    }
}

The issue lies within the anonymous function where I wish to use the values of subExt and ext. By the time the function is called though, the loop has caused the two variables to be assigned different values. I would like the function to use the values that the two variables had when the function was created.

I have tried many different ways in coming up with a solution. The most recent and closest being this:

module.exports[ext] = new Function(['options'], 
    `options.ext = "${subExt + ext}";
    (${sendRequest})(options);`
);

sendRequest() is a normal function, global in the module. The only reason this doesn't work is because this Function() constructor seems to create an isolated VM, sendRequest() calls another global function which it cannot access because of this. However, even if this did work I would be looking for an alternative because it's ugly as hell.

Extra/potentially useless: I've also tried it like this:

module.exports[ext] = function (options) {
    options.ext = this.subExt + this.ext;
    sendRequest(options);
}

module.exports[ext].subExt = subExt;
module.exports[ext].ext = ext;

But this seems to be undefined.

Please ask any questions if you don't understand! Thanks for your time :)

James Middleton
  • 679
  • 1
  • 5
  • 8

0 Answers0