0

I am learning nodejs by writing an app to manage my Philips hue lights and I have a problem with the way nodejs works.

I have a function that is supposed to get all ids of the lights:

id = [];

function getLightsId() {
    args = {
        path: {
            "username": "myusername"
        }
    };

    client.registerMethod("getLightState", "http://192.168.0.10/api/${username}/lights/", "GET");

    client.methods.getLightState(args, function (data, response) {
        for (key in data) {
            id.push(key);
        }
    });
}

The problem is that whenever I want to use my id array, its empty because nodejs didnt processed the getLightsId callback function.

ps : I am using node-rest-client to interact with my API.

lante
  • 7,192
  • 4
  • 37
  • 57
Jeremie4zw
  • 676
  • 2
  • 7
  • 17

2 Answers2

3

It processed your callback alright, it's just that the function is asynchronous. Meaning that when you try and use the id variable later on, it is still processing from the above callback. You need to pass in another callback and pass your id variable to that once it's been filled:

function getLightsId(callback){
    args ={
        path:{"username":"myusername"}
    };

    client.registerMethod("getLightState", "http://192.168.0.10/api/${username}/lights/", "GET");

    client.methods.getLightState(args, function(data,response){
        var id = [];
        for(key in data){
            id.push(key);
        }
        callback(id);
    });
}

And you would call this like:

getLightsId(function(idArray) {
    console.log(idArray); //here they are
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

Another aproach is to use a promises library, like promised-io, it's just one of the ways to avoid "callback hell".

var Deferred = require('promised-io/promise').Deferred;

id = [];

function getLightsId() {
    var deferred = new Deffered;

    args = {
        path: {
            "username": "myusername"
        }
    };

    client.registerMethod("getLightState", "http://192.168.0.10/api/${username}/lights/", "GET");

    client.methods.getLightState(args, function (data, response) {
        for (key in data) {
            id.push(key);
        }

        deferred.resolve();
    });

    return deferred.promise;
}

getLightsId().then(function(){
    // Now you have the id[]s
});
Drahcir
  • 11,772
  • 24
  • 86
  • 128
  • Well, i just want to store my id's in an array, so i can use this array in other functions easily. – Jeremie4zw Mar 28 '14 at 17:37
  • @user3473514, then this will work for you, I've left your `id` array in the global scope, and you'll be able to access it when the promise is resolved (where I commented). – Drahcir Mar 28 '14 at 17:38