使用firebase forEach快照后调用函数

时间:2019-10-12 19:11:01

标签: javascript firebase vue.js firebase-realtime-database promise

我想在forEach完成后调用外部函数。这是我的代码的结构:

  • 默认导出
    1. 安装功能
      • firebase foreach
        • 在这里,一旦完成,我想调用方法函数
    2. 方法功能
      • 调用计算函数
    3. 计算函数

我想使用诺言,但我不知道怎么做。

//inside the mounted function

//this is an aux vector, I want to push here the results of forEach
let aux = []

//here I'm login in firebase realtime database
firebase.auth().signInWithEmailAndPassword("user", "pass").then(function(user) {

    //here I want to read the database
    db.ref().once("value").then(function(snapshot) {

        //here I'm cycling on the fields of database
        snapshot.forEach(function(childSnapshot) {
          //here I'm saving the fields on the aux vector pushing them
          aux.push([childSnapshot.key, childSnapshot.val()])
        })

        //here I want to call the UpdateFoto function but I cannot since the "this" is only defined out of all this firebase function

    }).catch(function(error) {
        console.log("Error getting document:", error);})
}).catch(function(error) {
      let errorCode = error.code;
      let errorMessage = error.message;
      console.log(errorCode +" "+errorMessage)})

//here I can access to "this" selector, but without a promise or something it is executed before the forEach will finish his loop. I want to call the function after the forEach have finished
this.updateFoto(aux)

1 个答案:

答案 0 :(得分:2)

将函数转换为使用箭头函数语法,因为它们不会更改select n.id, n.title, coalesce(count(distinct c1.cid), 0) + coalesce(count(c2.cid), 0) "comments" from nodes n left join comments c1 on c1.entity_id = n.id and c1.entity_type = 'node' and c1.status = 1 left join comments c2 on c2.entity_id = c1.cid and c2.entity_type = 'comment' and c2.status = 1 group by n.id, n.title 的绑定。所以,而不是

| id  | title             | comments |
| --- | ----------------- | -------- |
| 1   | My first article  | 3        |
| 2   | My second article | 1        |
| 3   | My third article  | 0        |

使用

this

如果使用此语法,则function(snapshot) { ... } function(childSnapshot) { ... } 在外部作用域中将保持不变,并且将能够以您最初想要的方式调用(snapshot) => { ... } (childSnapshot) { ... }

关于JavaScript在各种情况下如何绑定this的信息很多。了解其工作原理将很有帮助。

How does the "this" keyword work?