Home > Net >  How to return value from async-await function?
How to return value from async-await function?

Time:09-09

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.

CodePudding user response:

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();

CodePudding user response:

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

CodePudding user response:

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

  • Related