一旦 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 回答
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
红糖糍粑
TA贡献1815条经验 获得超6个赞
将您的函数转换为使用箭头函数语法,因为它们不会更改this. 所以,而不是
function(snapshot) { ... }
function(childSnapshot) { ... }
用
(snapshot) => { ... }
(childSnapshot) { ... }
如果你使用这个语法,this从外部作用域将保持不变,并且你将能够以this.updateFoto(aux)你最初想要的方式调用。
有很多关于 JavaScriptthis在各种情况下如何绑定的信息。了解它是如何工作的会很有帮助。
添加回答
举报
0/150
提交
取消