0

I am new at node.js, so please be patient :)

What I need to do:

  • load from url Ids of users
  • Hit another url for every ID

What am I doing wrong?

var http = require('http');
var Client = require('node-rest-client').Client;

var client = new Client();

url = 'http://example.com/api/get-users';

client.get(url, function (data, response) {
    if (data.status == 'OK') {
      users = data.users;

      users.forEach(function(item) {
        newUrl = 'http://example.com/generateStats/' + item;
        client.get(newUrl, function(data, response){
          console.log(data);
        });
      });
    }
});

The value of users is: [1,2,4,5,7,...]

Nothing in forEach is executing, why?

zangw
  • 43,869
  • 19
  • 177
  • 214
Michal
  • 17
  • 5
  • Coul you check if the if block is executed? I think it should be "response.status == 'OK'". Also create users as a new var and don't write it into the global scope "var users = data.users;". This can cause unexpected errors like this one. – Herku Jan 25 '16 at 12:58

2 Answers2

0

I think you need something like async Check this answer: simplest-way-to-wait-some-asynchronous-tasks-complete-in-javascript

Community
  • 1
  • 1
user3611630
  • 137
  • 7
0

There is no status in data nor response so it never go inside the if block. To handle errors with node-rest-client, you have to listen to the error event:

var http = require('http');
var Client = require('node-rest-client').Client;

var client = new Client();

url = 'http://example.com/api/get-users';

client.get(url, function(data, response) {
  // if there is an error, this function is not executed
  var users = data.users;

  users.forEach(function(item) {
    newUrl = 'http://example.com/generateStats/' + item;
    client.get(newUrl, function(data, response) {
      console.log(data);
    });
  });
}).on('error', function(err) {
  console.log('something is wrong: ' + err.code);
});

There is a response.statusCode though, it returns an http code like 200.

Shanoor
  • 13,344
  • 2
  • 29
  • 40
  • My json file:{"status": "OK", "users": [1, 4, 13, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43]}. But console.log(data) returns '' ... Why? – Michal Jan 25 '16 at 14:11
  • @Michal Ah, my bad, `data` is a Buffer object, just do `data = data.toString()` to get a JSON and you'll be able to check `.status` on it. This `node-rest-client` is weird, most of modules detect JSON and don't return a Buffer. – Shanoor Jan 25 '16 at 14:20