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

227
Visualizações
How to store JSON in variable from fetch API

I can't disclose the URL and what API I'm using because it breaches my work's policy but hopefully, I can provide enough information for assistance. I have a JavaScript function that runs on an on-click (I'm eventually building up a form that will make use of this fetch).

function getdata() {
let customer_po = document.getElementById("customer").value;
let access_token;
let data = {
    'grant_type': 'REDACTED'
}
let state = {
    "state": "REDACTED"
}
fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
    .then(response => response.json())
    .then(result => console.log(result))
}

This works and I can access the dictionary in the console. However, when I try to use my access_token variable declared earlier in such a way:

.then(response => response.json())
.then(result => {access_token = result["access_token"];})

and console.log(access_token) gives undefined. I need to access this variable in my getdata() function so it can be used as a parameter in another fetch call.

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

0

If you defined and assigned a value to a variable synchronously as you typically do, that variable is available until you leave its scope. For the purpose of this explanation (and generally), JavaScript variables are scoped to the function they run in e.g.

var myVariable = 'acb123';
console.log(myVariable); // 'abc123'

var myFunc = function() {
  var myFunctionVariable = 'def456';
  console.log(myFunctionVariable); // 'def456'
};

console.log(myFunctionVariable); // Uncaught ReferenceEError: myFunctionVariable is not defined

Since you're using promises, you're handling the result of a non-synchronous assignment via functions and the variables you use in each of those callback functions is scoped only to within those functions. While there's no issue in taking a currently scoped variable and writing it out to the console, you'll have the issue you describe when you try to use a variable that's assigned in another non-parent function. You can access the dictionary in your console because you're not actually accessing the variable at that point - you're accessing the object saved in your console.

Going back to your fetch statement, it's making an asynchronous call, so it's not even going to immediately return anything but a promise when assigned. You've already figured out that if you want to do anything with the promise result when it is populated, you need to do so in a chained .then() method. What you're trying to do is then take this asynchronous result and pass it into a variable used and called synchronously and that's not going to work.

Rather, everything you're wanting to do, you must do in subsequent then() methods:

 fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
  .then(response => response.json())
  .then(result => result["access_token"])
  .then(access_token => {} //Call your next fetch method);

Especially if you're looking at doing more elaborate chains of asynchronous operations, you might also look at using RxJS to somewhat simplify mappings across different chained operations.

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