我想在forEach完成后调用外部函数。这是我的代码的结构:
我想使用诺言,但我不知道怎么做。
//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)
答案 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
的信息很多。了解其工作原理将很有帮助。