How to use Promise in Firebase Query?

0

I need to make basic promises like this:

1) Will do a query in Firebase, checking if there is a certain ID. If there is this ID, it will give the .then saying that it is ok and do something, if it will not give the .catch, stating the problem.

What I tried to do was the following: But I do not think I did it the right way.

 this.queryMAP = () => {
        //let userId = this.getDBSReference().currentUser.uid;
        let mapRef = this.getDBSReference().ref('users/Aliansce/LOCATIONS/').orderByKey().equalTo('map1');
        mapRef.on('child_added', (snap) => {
            console.log(snap.key)
            snap.key.this.createPromise()
    });

    this.createPromise = () => {
        let promise = new Promise((resolve, reject) => {
            console.log(snap.key)
            if(snap.key == "map1"){
                resolve("igual")
            } else {
                reject("diferente");
            }
        }).then((sucess) =>{
            console.info("ae");
        }).catch((err) => {
            console.warn("error")
        });
    };
    
asked by anonymous 12.01.2018 / 18:17

1 answer

0

From what I understand, you want a location through your key (id). I suggest that you use the once() function. Per documentation once() returns a Promise.

Then you would:

this.queryMAP = () => {
        //let userId = this.getDBSReference().currentUser.uid;
        let mapRef = this.getDBSReference().ref('users/Aliansce/LOCATIONS/').child('map1');
        mapRef.once('value').then((snap) =>{
            console.log(snap.key);
            console.info("ae");
        }).catch((err) => {
            console.warn("error");
        });
    };
    
14.01.2018 / 11:26