猿问

在使用 firebase forEach 快照后调用函数

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


导出默认值

挂载函数

火力点 foreach

在这里,一旦完成我想调用一个方法函数

方法功能

调用计算函数

计算函数

我想使用 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)


米脂
浏览 93回答 1
1回答

红糖糍粑

将您的函数转换为使用箭头函数语法,因为它们不会更改this. 所以,而不是function(snapshot) { ... }function(childSnapshot) { ... }用(snapshot) => { ... }(childSnapshot) { ... }如果你使用这个语法,this从外部作用域将保持不变,并且你将能够以this.updateFoto(aux)你最初想要的方式调用。有很多关于 JavaScriptthis在各种情况下如何绑定的信息。了解它是如何工作的会很有帮助。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答