1

I'm starting in the world of promises and there is one thing I can't understand.

I am trying to make a system that returns a document from a Firebase collection by its ID.

For this I use 2 functions

 const getProductDataById = async(idProduct)=> {
    
        const docSnap = await getDoc(doc(db, "products", idProduct));
        if (docSnap.exists()) {
            return docSnap.data();       
        } 
        else {  
            console.log("No such document!"); 
        }
    }


    const getProduct = (idProduct)=>{
        
        let ProductDataPromise = getProductDataById (idProduct);
        
        //I don't know how resolve Promise

        return ProductData;
       
        
    }

The problem is that I don't know in the second how to resolve the Promise so that this function returns the desired object.

Thanks!!

Marcvilap
  • 23
  • 3

2 Answers2

1

You should be able to just await the call to the first function:

const getProduct = async (idProduct)=>{
  let ProductData = await getProductDataById(idProduct);
  // Do something with ProductData?
  return ProductData;      
}

Of course, if you're not doing anything with ProductData, then this is equivalent to just calling getProductDataById directly.

Alan Friedman
  • 1,582
  • 9
  • 7
  • It's important to mention that you made getProduct async as well in order to use await. That's not a trivial change, as it implies that the caller of getProduct also must await or use then/catch to get the final result. – Doug Stevenson Jul 16 '22 at 16:16
0

I was experiencing the same problem. Maybe you've already solved it... but here's my example:

async function login({email, password}: RegisterAndLoginData) {
    await signInWithEmailAndPassword(auth, email, password)
        .then(===>async<===(data) => {
            const uidDocUsers = data.user.uid;
            const docRef = doc(db, "users", uidDocUsers);

            //returns only array with user data
            const getNameUser ===>await<=== getDoc(docRef)
                .then((data) => {
                    ===>return data.data().name<=== //I just wanted a specific data, name

                }) 
                
            console.log("Document data:", getNameUser);

            // console return: Document data: "Bianca :D"
        })
        .catch((error) => {...}

Always be careful and analyze very well where to put async/await