0

I'm building a blog and for each blog post I'm trying to include the authors name, rather than the authors ID.

I have two functions: getUserName and mapData.

mapData remaps the blog object:

function mapData(posts) {
    let result = [];
    result = posts.map(post => ({ 
        id: post._id,
        title: post.title,
        imageURL: post.imageURL,
        body: post.body,
        author: getUserName(post.createdBy),
        date: date(post.createdAt) 
    }));
    console.log(result)
    return result;
}

getUserName gets the users name:

const getUserName = async id => {
    try {
        const getUser = await User.findById(id)
        console.log(getUser)
        return getUser.firstname;
    } catch (err) {
        throw err;
    }
}

But after console logging the result in mapData the value for author is Promise { <pending> }. Can anyone explain why this is happening? I thought by using an async function would avoid this?

user10230515
  • 93
  • 1
  • 7

1 Answers1

0

An async function returns a Promise. The easiest thing to do here would be to mark the map cb as async as well and then await getUserName();

As mentioned in the comments this can get a bit messy because you'd be dealing with many more Promises afterwards. If you'd rather not deal with that and you're using MongooseJS you could use Populate, for the author field which will simply return the data you need with only one call on your part.

Alex D
  • 970
  • 6
  • 13