【问题标题】:Call a function after snapshot forEach with firebase使用firebase在快照forEach之后调用一个函数
【发布时间】:2020-02-09 22:41:21
【问题描述】:

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

  • 导出默认值
    1. 挂载函数
      • firebase foreach
        • 在这里,完成后我想调用一个方法函数
    2. 方法函数
      • 调用计算函数
    3. 计算函数

我想用promise,但不知道怎么用。

//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)

【问题讨论】:

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


    【解决方案1】:

    将您的函数转换为使用箭头函数语法,因为它们不会更改this 的绑定。所以,而不是

    function(snapshot) { ... }
    function(childSnapshot) { ... }
    

    使用

    (snapshot) => { ... }
    (childSnapshot) { ... }
    

    如果您使用此语法,this 将保持外部范围不变,您将能够以您最初想要的方式调用 this.updateFoto(aux)

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

    How does the "this" keyword work?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 2021-12-27
      • 2018-01-17
      • 2020-01-18
      • 1970-01-01
      相关资源
      最近更新 更多