My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

How can I return a value from inside a promise that is in another function in Javascript?

Utkarsh Bhatt's photo
Utkarsh Bhatt
·Mar 9, 2018

I have this function called getUserData which takes in the user's mobile and returns their userRecord object by checking it in Firebase Authentication.

I want the code to be such that when I call the getUserData('some mobile here'), it should return me the user's userRecord object from Firebase.

In the code below, it is returning undefined on calling the getUserData with correct arguments even if the user exists in the auth.

const getUserRecordFromAuth = mobile => {
    const promise = auth.getUserByPhoneNumber(mobile);
    /*
     * userRecord: {
     *    uid: '52348348934534h5',
     *    name: 'ABC'
     *    mobile: '9090909090'
     * }
     */
    return promise.then(userRecord => {
        return userRecord;
    }).catch(error => {
        console.log(error);
    });
}

const getUserData = mobile => {     
    return userRecord = getUserRecordFromAuth(mobile)
         .then(data => {             
            return data;         
    }); 
}

I think that the issue is with how promises work. Can someone please explain how I can do what I explained above? Any help would be appreciated.

This is Firebase API BTW.