Getting value from function with callback paramete

2019-08-13 23:09发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-08-13 23:41

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();
});
查看更多
登录 后发表回答