使用回调参数从函数中获取值 [英] 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)
});
文档链接此处
推荐答案
您可以在调用函数时将回调函数中的值添加到数组中.可能看起来是这样:
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);
啊,那是因为控制台日志是在实际 .push 完成(未同步)之前处理的.尝试将进一步处理代码放入回调函数中,例如:
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
});
使用异步循环
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;
}
你可以像这样使用它:
asyncLoop(iterations, function(loop)
{
//Iterations here
theParam.get(function(value)
{
myArray.push(value);
loop.next();
});
}, function()
{
//Finished loop
callback();
});
这篇关于使用回调参数从函数中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!