0

Please note: I m posting this question becuase I could not find a soultion to my problem from similar other questions. Any help in this regard would be gretaly appreciated.

I have a function:

const getUsenameProps =  (id: string) => {
    const userNameProps: IUserName = {
    friendName : getFriendName(id).toString(),
    friendId : id
    }
    console.log("AAAAAAAAAAAAA", userNameProps) //{friendName: Promise<string>, friendId: 1}
    return userNameProps
}

and the called function is like this

export const getFriendName =  async (id: string) => {
    const friendContact = await getUserData(arrayArgument,id)
    const friendName = friendContact && friendContact .id !== "" ?  friendContact .name : ""
    console.log("friendame") //sam
    return friendName 
}

Now, when I call the getUsernameProps(), it inturn calls the getFriendName() and this makes an API call. The console.log in getFriendName() prints a normal string ("sam"), and I am returning this. But when this is called in getUserNameProps, the value it is getting back is a Promise. I want to set userNameProps.friendName to the friendName value ("sam") returned in fetFriendName.

Please help

Chaitra D
  • 177
  • 3
  • 14
  • 2
    `async` functions [always return a Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value). That is what makes it possible to `await` them. – romellem Oct 07 '21 at 13:39
  • How can I return a string, or what should be the work around to get a string. – Chaitra D Oct 07 '21 at 13:42
  • `getUsenameProps` should also be `async` so you can `await` for the promise to resolve: `friendName: await getFriendName(id)`. You probably don't need that `toString()` because it's clearly already a string. – Andy Oct 07 '21 at 13:45
  • I want getUserNamePros to return a object. If I change that to async, then it will return a Promise instead of an object – Chaitra D Oct 08 '21 at 04:56

0 Answers0