skip to Main Content

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

3

Answers


  1. 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();
            ….}
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. If you check the reference docs for on you’ll see that it doesn’t return a Promise, so you can’t await its results. Use once (or get) instead:

    function GetUsername() {
      return database()
          .ref('/users/prathik1')
          .once('value')
          .then((snapshot) => snapshot.val());
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search