0

I would like to return user's phone number but what I got is [object Object]. Im thinking if it return the value before await is done.Here is my code.

//assume phone number is 12345678

async function user_attr() {
    try{
    const { attributes } = await Auth.currentAuthenticatedUser();
    console.log(JSON.stringify(attributes.phone_number)); //output:12345678
    return (JSON.stringify((attributes.phone_number)))
    } catch (e) {
        console.log(e);
    }
}

console.log('return='+user_attr()) //output: return=[object Object]

console.log('return='+JSON.stringify(user_attr())) //output: return={"_U":0,"_V":0,"_W":null,"_X":null}

To output 12345678 so that i can access it outside async function. For example to show it in profile page, <Text>phone_number</Text>

Any way to save phone number string into the a constant outside async funcition?

Jess
  • 63
  • 6
  • `return` will do it - your problem is how to access the returned value - `async` functions return a `Promise` - so you need to either `await` the promise or use `.then` – Jaromanda X Sep 09 '22 at 07:03

3 Answers3

0

You need to await the calling function as well. Async function always return Promise that are needed to await.

async function getPhoneNumber() {
  const phone = await user_attr();

  console.log('return='+phone)
}

getPhoneNumber();
  • Thanks for your answer! Is there way to save the phone number string to a constant that is outside any async function? – Jess Sep 09 '22 at 11:38
  • there're only two ways to get values from promises. 1. use await 2. use .then() callback. You cannot synchronously get a value from a function which return promise. – Tauqeer Nasir Sep 09 '22 at 13:35
0

YOu are returning a promise hence you need to do

  const checkFunction = async() => {
const promiseRes = await user_attr()
    
    console.log('return='+promiseRes ) 
    
    console.log('return='+JSON.stringify(promiseRes)) //output: ret
    }

Hope it helps

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45
0
async function user_attr() {
    try {
        const { attributes } = await Auth.currentAuthenticatedUser();
        //It is similar to "return new Promise(function (resolve) { resolve(attributes.phone_number) });"
        return attributes.phone_number;
    } catch (error) {
        console.log(error);
    }

}

//then((phone_number) => console.log("return=" + phone_number))

user_attr().then(function (phone_number) {
    console.log("return=" + phone_number);
})

//or async await

async function log_user_attr_phone_number() {
    const phone_number = await user_attr();
    console.log("return=" + phone_number);
}

log_user_attr_phone_number();

async function docs

iolduncle
  • 1
  • 1