问题描述
我将Firebase调用函数的返回值分配给我的全局变量时遇到了麻烦。这是我的功能:
pre $函数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 {
//完成函数创建路径 - 返回值
return path.name();
}
})
}
这是我设置请求的其他文件:
var base = new Firebase(path / to / my / base);
var output = getThePushNameById(base,2)
console.log(output);
所以我的问题是 console.log
不会等待定义 output
,但会自行运行并记录 undefined
。我的问题是,如果有人知道我怎样才能使 console.log
等待值?
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); //这里是错误
})
} else {
//完成路径创建时的函数 - 返回值
callback(path.name());
}
})
}
getThePushNameById(base,2,function(output) {
console.log(输出);
});
创建了一个错误:当函数再次调用自身时,回调没有被定义,所以它返回一个未定义的值。这段代码现在可以正常工作了。
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);
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从回调返回(定时)赋值给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!