gpt4 book ai didi

javascript - 如何将其他变量传递到 Javascript 中的 Firebase promise 回调中?

转载 作者:行者123 更新时间:2023-11-29 10:06:44 26 4
gpt4 key购买 nike

我们正在尝试将其他变量传递到 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

关于javascript - 如何将其他变量传递到 Javascript 中的 Firebase promise 回调中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41926695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com