0

Unsure how to access the values date and prices else where in the script

fetch("fileName")
.then(response => response.json())
.then(data => {
    var date  = data.JSONdata[data.JSONdata.length - 1].date
    var prices = data.JSONdata[data.JSONdata.length - 1].prices
})
logan9997
  • 73
  • 1
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) and [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – evolutionxbox Jan 02 '22 at 14:53
  • 1
    Not "elsewhere". You can only access them in that `then` callback. Place your code that uses `date` and `prices` right after their `var` declarations. – Bergi Jan 02 '22 at 14:58

2 Answers2

1

You can simply rewrite your code to use async/await:

const response = await fetch("fileName");
const data = await response.json();
const date  = data.JSONdata[data.JSONdata.length - 1].date;
const prices = data.JSONdata[data.JSONdata.length - 1].prices;

EDIT: To use this asynchronous code, you have to define the function in which you use this code as async:

async function yourFunction() {
    // your async code from above
}

// await async function where it's called
const functionResult = await yourFunction();

You have to make every function in your callstack async up to the level where you no longer care about the response. So the function which calls "yourFunction()" has to be async aswell. And so on.

peaxkl
  • 71
  • 4
0

You can use await to get the Promise result. Please refer MDN docs

In the given example date and prices are hard-coded which will be fetched via API calls in real-scenario

const date = Date.now();
const prices = [1000, 2000];
const resolvedProm = Promise.resolve({date, prices});

let thenProm = resolvedProm.then(({date, prices}) => {
    return {date, prices};
});

let res = await thenProm;
console.log(res); 
// {date: 1641136463085, prices: Array(2)}
Nikhil Pathania
  • 812
  • 6
  • 19