Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
return json value through fetch function

I am trying to output the players name from a JSON array using fetch and just returning it where I call it at for, I can insert the return into html elements.

The console logs the results I want perfectly but the return, returns undefined in the element.

JSON api example:

{
    "PlayerID": 10000439,
    "Jersey": 8,
    "Position": "RF",
    "FirstName": "Nick",
    "LastName": "Castellanos"
}

HTML

<div id="scoreboard">
        <div class="home">TEAM1<span class="runs"></span>0</div>
        <div class="away">TEAM2<span class="runs"></span>0</div>
    </div>
    <div class="batting">
        Batting:
        <span id="batterPlayerName">
        Player Name
    </span>
    </div>
    <div class="pitching">
        Pitching:
        <span id="pitcherPlayerName">
        Player Name
    </span>
    </div>

JS

function PlayerName(id) {
     var url = `https://apiurl/Player/${id}`;
     fetch(url)
     .then(response => response.json())
     .then(data => {
         console.log(`${data.FirstName} ${data.LastName}`)
         return data.FirstName + ' ' + data.LastName;
     })
}



var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');

curBatter.innerHTML = PlayerName('10000439');
curPitcher.innerHTML = PlayerName('10000526');

console: Nick Castellanos PlayerName div: Batting: undefined

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

You are attempting to set the value of PlayerName before the fetch has resolved.

If you return the promise from your PlayerName function then you are able to set the innerHtml once the promise is resolved.

function PlayerName(id) {
    var url = `https://apiurl/Player/${id}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => {
            console.log(`${data.FirstName} ${data.LastName}`)
            return data.FirstName + ' ' + data.LastName;
        })
}

PlayerName('10000439').then(player => {
    var nameDiv = document.querySelector('#PlayerName')
    nameDiv.innerHTML = `Batting: ${player}`;
})

Alternatively you can wrap the entire function to execute asynchronously

async function PlayerName(id) {
    var url = `https://apiurl/Player/${id}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => {
            console.log(`${data.FirstName} ${data.LastName}`)
            return data.FirstName + ' ' + data.LastName;
        })
}



var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');


(async () => {
    curBatter.innerHTML = await PlayerName('10000439');
    curPitcher.innerHTML = await PlayerName('10000526');
})();
about 4 years ago · Santiago Gelvez Relatório

0

You must declare the HTML selector to the belonging JSON

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda