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

时间:2017-01-29 22:31:15

标签: javascript callback 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()未定义的错误。

我们如何将其他变量参数传递给我们的承诺回调?

1 个答案:

答案 0 :(得分:4)

我们在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