微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Javascript中将其他变量传递到Firebase Promise的回调中?

我们正在尝试将其他变量传递到Firebase .ON promise的回调中.
我们看过SO上的数十篇文章,描述了如何将静态变量传递给.ON方法的回调函数-但是每个版本都会为我们抛出data.val()未定义错误.

这是示例代码.我们要为i传递一个值:

var path = firebase.database().ref(our_firebase_data_url);
var fx = function fx_call(data) {
    value = data.val();
    console.log("Here is your passed parameter: " + i); // we want this defined 
};
path.on('value', fx);

我们以为我们也许可以做这样的事情,但我们无法对此进行改进:

fx_call(data,i) { 
     value = data.val();
     i = i.val(); 
};

或者,看起来我们可以通过.bind语句传递值

fx_call(data,i) { 
     value = data.val();
     i = i.val(); 
}.bind(this, i) # we also tried .bind(null,i) and .bind(i)

但是,我们从多个SO帖子(123等)尝试的每种方法都为我们带来了data.val()未定义错误.

我们如何将其他可变参数传递给我们的promise的回调?

解决方法:

我们在SO之外找到了一个答案,因此我们要求在此处添加答案.

您可以使用以下格式的.bind语句将变量传递到包括Firebase Promise回调在内的函数中:

 fx_call(data,i) { 
         value = data.val();
         i = this.i; # this is how you access the value from the bind
         j = this.j; 
 }.bind( {i: i, j: 10} ) # this is how you pass variables into the callback function...this.i will be whatever value the scope of i was at the time the function was created...this.j in this case will be 10

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐