Home > Software engineering >  Async Await not working reading data from Firebase with react native
Async Await not working reading data from Firebase with react native

Time:11-11

This is my current code (see image) I need my OwnProfile function to wait for my GetUsername function to finish reading data from firebase before continuing. I tried async await, but it is not working as shown in the terminal where line 52 and 54 are used before GetUsername has gotten the data.

Anyone got any tips to fix this?

enter image description here

CodePudding user response:

you need to await GetUsername method so that console.log could get executed once data has response

async function OwnProfile ({navigation}){
        const data = await GetUsername();
        ….}

CodePudding user response:

Since you're working with a callback function in GetUsername(), you must return a Promise which is to be resolved in the callback function code, like this:

async function GetUsername() {
    return new Promise((resolve, reject) => {
        database()
            .ref('/users/prathik1')
            .on('value', snapshot => {
                resolve(snapshot.val());
            });
    });
}

With this you should be able to do

const result = await GetUsername();

Note: This is only an incomplete example. Take care of calling reject() in case an error occurs.

  • Related