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

192
Visualizações
Javascript POST/GET Fetch request - need to access data outside of request

I'm trying to access the data returned inside my POST request, outside of the request, preferably made available globally so I can access it in other functions. What I'm really trying to do is access specific JSON data and make changes to it via other functions and PUT/GET requests (I'm making a command line guessing game.)

NOTE: I've seen a lot of this same question on here but I can't figure out how any answer pertains to my code/none of the answers are really what i'm looking for. I would like to know what step I'm missing in my own code to help me accomplish this.

Here is my code so far. I know I'm close but I'm stuck at this point.

const apiUrl = 'https://word-guessing-game.onrender.com'

let jsondata = "";
    
    async function getJson(url) {
        let response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        let data = await response.json()
        let gameId = data.game.id
        return gameId
    }
    
    async function main() {
        getJson(apiUrl)
            .then(data => console.log(data));
    }
    
    main();

Right now I have this setup to just return the game.id, because that's what i'm trying to access with a separate function/get request. Any help is appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This is the way you can use your async data by another function

const apiUrl = 'https://word-guessing-game.onrender.com'

    
    async function getJson(url) {
        let response = await fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        let data = await response.json()
        let gameId = data.game.id
        return gameId
    }
    
    function processData(data) {
         console.log(data)
    }
    
    async function main() {
        const data = await getJson(url)
        processData(data)
    }
    
    main().then();

So as you probably know, the javascript is executed from up to down, so lets see whats happening there:

  1. We declare a constant apiUrl
  2. We declare an async function getJson
  3. We declare an ordinary function processData
  4. We declare another async function main
  5. We not at long last call our main function, which calls getJson, where we pass our apiUrl as a param. the await key allows us to "wait" for the result from the function so we can access it with our processData function

PS. .then() I used because usually most IDE and inspecting tools are not happy when you call a function which returns a Promise, which you ignore.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you are using async/await, why not use it like this:

let jsonData = await getJson(apiUrl)
// jsonData will receive the value which getJson is returning
// in this case, the game id.

If you must use .then syntax, you will have to pass a callback to update the value of jsonData

// in getJson function pass another callback
async function getJson(url, cb) {
.
.
.

let data = await response.json()
let gameId = data.game.id
cb(gameId);

And your cb function can look like this

function cb(data) {
  jsonData = data; // same json data declared at the top
}
about 4 years ago · Juan Pablo Isaza 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