Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda