Вызов функции после снимка для каждого с помощью firebase - PullRequest
0 голосов
/ 12 октября 2019

Я хочу вызвать внешнюю функцию после завершения forEach. Это структура моего кода:

  • экспорт по умолчанию
    1. смонтированная функция
      • fireachase foreach
        • здесь, после завершения я хочу вызватьметоды методы
    2. методы функции
      • вызов вычислительной функции
    3. вычисляемая функция

Я думаю использовать обещание, но я не знаю как.

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

1 Ответ

2 голосов
/ 12 октября 2019

Преобразуйте ваши функции в синтаксис функции стрелок, поскольку они не изменяют привязку this. Таким образом, вместо

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

Используйте

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

Если вы используете этот синтаксис, this останется неизменным из внешней области, и вы сможете вызывать this.updateFoto(aux)как вы изначально хотели.

Существует много информации о том, как JavaScript связывает this в различных ситуациях. Будет полезно узнать, как это работает.

Как работает ключевое слово "this"?

...