john edgar otom
john edgar otom

Reputation: 153

how to return async await promise

I am currently working on getting all the Data object from a certain user. I thought I am already getting it, but then I noticed that it only return a DATA the second time I click the button ( means async is not working ) If you can advice, that would be a great help! Thanks!

async getData(UID) {
let container = [];
var firebaseRef = this.afd.database.ref();

  let qwee = await firebaseRef.child('AllData/')
  .orderByChild("UserID")
  .equalTo(UID)
  .on("child_added", function(snapshot) {

      container.push(snapshot.val());

  }); 

return container;
}

This is the calling function

async LoadUserData(){
this.Data = await this.provider.getData("Tom");
}

Upvotes: 1

Views: 201

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29614

You seem to be mixing callbacks and promises.

You will need to wrap the callback in a promise and then await it.

async getData(UID) {
    let container = [];
    var firebaseRef = this.afd.database.ref();

    let qwee = await new Promise(function(resolve,reject){
       return firebaseRef.child('AllData/')
          .orderByChild("UserID")
          .equalTo(UID)
          .on("child_added", function(snapshot) {
              resolve(snapshot.val());
              //container.push(snapshot.val());

           });
        }); 
    container.push(qwee);
    return container;
}

Upvotes: 1

Related Questions