简体   繁体   English

通过回调参数从函数中获取价值

[英]Getting value from function with callback parameters

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 在此处链接到文档

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). 编辑:啊,这是因为在完成实际的.push(未同步)之前已处理了控制台日志。 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM