为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

米脂 2021-11-18 17:14:58
一旦 forEach 完成,我想调用一个外部函数。这是我的代码结构:导出默认值挂载函数火力点 foreach在这里,一旦完成我想调用一个方法函数方法功能调用计算函数计算函数我想使用 promise,但我不知道如何使用。//inside the mounted function//this is an aux vector, I want to push here the results of forEachlet aux = []//here I'm login in firebase realtime databasefirebase.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 finishedthis.updateFoto(aux)
查看完整描述

1 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

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


function(snapshot) { ... }

function(childSnapshot) { ... }


(snapshot) => { ... }

(childSnapshot) { ... }

如果你使用这个语法,this从外部作用域将保持不变,并且你将能够以this.updateFoto(aux)你最初想要的方式调用。


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


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信