1

I am working on a Javascript, HTML and CSS proyect. What I want is to get the name of a user using its Id. I use fetch to do that but I am getting some problems.

function getUserName(userId) {
  let userTemp = window.API_HOST + '/users/' + userId;
  return fetch(userTemp, {
    headers: { authorization: localStorage.access_token },
  })
    .then(response => response.json())
    .then(response => {
      console.log('El nombre es: ' + response.name);
      return response.name;
    });
}

The problem here is that response.name is a promise object and not the actual name. I tried to use stringify but it did not work. Any suggestions?

EDIT: I need to call that function in a place like this:

function showOffer(newOffer) {
  if (newOffer.user_id === JSON.parse(localStorage.current_user)._id) {
    const wrapper = document.createElement('div');
    wrapper.className = 'wrap';
    const prodHolder = document.getElementById('demo').appendChild(wrapper);

    const offerBidderId = document.createElement('p');
    const offerBidderIdText = document.createTextNode(
      'Bidder id: ' + getUserName(newOffer.bidder_id),
    );
    console.log('New offer bidder id ' + newOffer.bidder_id);
    offerBidderId.appendChild(offerBidderIdText);
    wrapper.appendChild(offerBidderId);
    ....
}

Maybe here is the problem?

Mauricio Estevez
  • 419
  • 1
  • 6
  • 21

1 Answers1

1

fetch returns always a Promise. So you have to handle it with then or async/await.

You can access it like this:

getUserName(1).then(name => {
   console.log('El nombre es: ' + name);
});

or inside an async function:

async function access() {
    const name = await getUserName(1);

    console.log('El nombre es: ' + name);
}

Nice article about async functions: https://developers.google.com/web/fundamentals/primers/async-functions

Philip
  • 3,486
  • 1
  • 24
  • 37