1

Im trying to append the value I get in console log, to an array, but I keep getting undefined. I think the function is asynchronous thats why when i try to access it's undefined at time of execution. From what I understand from documentation is that its function parameters is a callback parameter, can someone tell me how to use the value I get to append to an array or a dict.

    var theparam = new ROSLIB.Param({
            ros : ros,
            name : formid.elements[i].name
        });


    theparam.get(function(value) {
            console.log(value)
        });

link to documentation here

1

1 Answer 1

1

you can just add the value from the callback function to your array, when the function is invoked. May look so:

var myArray = [];

theparam.get(function(value) {
    myArray.push(value);
});

console.log(myArray);

Edit: Ah that's because the console-log is processed before the actual .push is done (unsynchronized). Try to put the further processing code into the callback function like:

theparam.get(function(value) {
    myArray.push(value);
    console.log(myArray);
    //Further code here
});

Edit with async loop:

function asyncLoop(iterations, func, callback)
{
var index = 0;
var done = false;
var loop = null;
loop =
{
    next: function()
    {
        if (done)
        {
            return;
        }

        if (index < iterations)
        {
            index++;
            func(loop);
        } else
        {
            done = true;
            callback();
        }
        ;
    },

    iteration: function()
    {
        return index - 1;
    },

    // break: function()
    // {
    // done = true;
    // callback();
    // }
};
loop.next();
return loop;

}

And you can use it like:

asyncLoop(iterations, function(loop)
{
    //Iterations here
    theParam.get(function(value)
    {
        myArray.push(value);
        loop.next();
    });
}, function()
{
    //Finished loop
    callback();
});
Sign up to request clarification or add additional context in comments.

2 Comments

just put the further processing into the callback-function from theparam.get()
well in that case you can wait after your loop until all callbacks are captured (with a simply flag-map) or you implement an asynchrone loop by yourself (where the next iteration is invoked as a callback is called). This may look like a new edit...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.