简体   繁体   中英

Passing a variable to inline function within a for loop in javascript

I have been trying to get this working

var http = require('http'),
    parseString = require ('xml2js').parseString;

for (var noOfZones = 1; noOfZones<=8; noOfZones++) {
    var newPath = 'http://192.168.1.200/getZoneData?zone='+noOfZones;
    var req = http.request(newPath, function(zres, noOfZones) {
        zres.setEncoding('utf8');
        zres.on('data', function (zonedata) {
            parseString(zonedata, {
                trim:true,
                childkey:9,
                explicitArray:false,
                explicitChildren:false
            }, function (err, zones) { 
                   console.log(noOfZones);//this one bring back undefined
            });
         });
     });
     req.on('error', function(e) {
        console.log('problem with request: ' + e.message)
     })
     req.end();
}

The for loop works ok for passing the noOfZones to newPath. However the value is not being passed through within the function (err, zones) I have been reading on passing the variables to inline functions and attempted to place it at various levels but it doesn't seem to be working for me. All I get back is undefined. (Even if i stringify it)

What makes you think request will pass additional arguments to your callback?

You can do the following:

var http = require('http'),
    parseString = require ('xml2js').parseString;

Array.apply(null, new Array(8)).forEach(function(_, i) { //make iterable array
    var noOfZones = i + 1; //define scope variable
    var newPath = 'http://192.168.1.200/getZoneData?zone='+noOfZones;
    var req = http.request(newPath, function(zres) {
        zres.setEncoding('utf8');
        zres.on('data', function (zonedata) {
            parseString(zonedata, {
                trim:true,
                childkey:9,
                explicitArray:false,
                explicitChildren:false
            }, function (err, zones) { 
                   console.log(noOfZones); //access it
            });
         });
     });
     req.on('error', function(e) {
        console.log('problem with request: ' + e.message)
     })
     req.end();
});

Should work if you get rid of the "var" before noOfZones in the loop declaration. So for (noOfZones = 1; noOfZones<=8; noOfZones++) instead of for (var noOfZones = 1; noOfZones<=8; noOfZones++) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM