0

I'm brand new to Node.js and I'm having a small issue which might have something to do with my understanding of Node.

Basically, I'm trying to create a bunch of severs (each one on a different port) to emulate a situation where my app would be calling out to multiple clients. However, when I loop, I'm trying to make them have an endpoint that returns their "ID", but for some reason it always returns the final value of i, 19, rather than the index that I stored during with client.set during the loop. Am I missing something simple? Here's my server.js:

    var express = require('express');

    var clientcount= 20;
    var clients= new Array();

    for (var i=0; i < clientcount; i++) {

        var client= express();

        client.set('id', i);

        client.get('/', function(req,res) {

            console.log("Pinged " + client.get('id'));
            res.send("Hello world from " + client.get('id'));

        });

        clients.push(client);

        console.log("Test value: " + clients[i].get('id'));

        clients[i].listen(3001 + i);
        console.log("Client listening on port " + (3001 + i));

    }

In this example, the "Test Value" prints out as expected, but if I use postman to hit say, 127.0.0.1:3014, I get 19 instead of 13 as expected.

SleepyProgrammer
  • 443
  • 1
  • 5
  • 15
  • Comment by @benjamin-gruenbaum solved the issue with this http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example. Thanks! – SleepyProgrammer May 12 '14 at 13:26
  • 2
    Glad I could help, this is a very common problem in JavaScript, in EcmaScript6, a `let` can help mitigate this. – Benjamin Gruenbaum May 12 '14 at 13:27

1 Answers1

1

I don't know how express class looks but I'd sniff there — seems that you assign the same instance of this object into newly created client variable in each iteration. Don't you need to create new instance instead?

dond
  • 138
  • 7