javascript从回调返回(计时)为变量赋值 [英] javascript assigning value to variable from callback return (timing)
问题描述
我在将 Firebase 调用函数的返回值分配给我的全局变量时遇到了问题.这是我的功能:
I'm having a trouble with assigning return value from Firebase call function to my global variable. This is my function:
function getThePushNameById( path , id ){
path.once( 'value', function( data ){
if( data.child('id').val() != id ){
data.forEach( function( newData ){
var base = new Firebase( path.child( newData.name() ).toString() );
getThePushNameById( base, id );
})
}else{
//finishes the function when path is founded - returns the value
return path.name();
}
})
}
这是我设置请求的另一个文件:
and this is the other file where I set the request:
var base = new Firebase(path/to/my/base);
var output = getThePushNameById( base , 2 )
console.log(output);
所以我的问题是 console.log
不等待 output
被定义,而是自己运行并记录 undefined
.我的问题是,如果有人知道如何让 console.log
等待值?
So my problem is that console.log
doesn't wait for output
to be defined, but runs itself and logs undefined
. And my question is if someone knows how can I make console.log
wait for value?
推荐答案
function getThePushNameById( path , id, callback ){
path.once( 'value', function( data ){
if( data.child('id').val() != id ){
data.forEach( function( newData ){
var base = new Firebase( path.child( newData.name() ).toString() );
getThePushNameById( base, id , callback ); //here was the error
})
}else{
//finishes the function when path is founded - returns the value
callback(path.name());
}
})
}
getThePushNameById( base, 2, function(output) {
console.log(output);
});
发现一个错误:当函数再次调用自身时,回调没有返回定义,所以它返回了一个未定义的.这段代码现在可以正常运行了
founded an error: callback was not back defined when function called itself again, so it returned an undefined. this code is now ok and works well
这篇关于javascript从回调返回(计时)为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!