1

I have a helper function(fetchData.js is the file name) which will send an array of json like this..

export const jsonData = async (file) => {
    const response = await fetch(file);
    const jsonData = await response.json();
    return jsonData;
};

Now I want to utilize this helper in some other file ,

import { jsonData } from './fetchData.js';

jsonData('./data2.txt').then((data) => {
    console.log(data);
});

and Its showing data perfectly, absolutely no issue..!!

enter image description here

But if I do something like this,

import { jsonData } from './fetchData.js';

let returnedData;
jsonData('./data2.txt').then((data) => {
    returnedData = data;
});
console.log(returnedData);

it returns undefined..

enter image description here

How to do ?

Edit :

enter image description here

Babai
  • 33
  • 7
  • move the console.log inside the `then` just below the `returnedData = data;` All your operations with `returnedData` should be inside the `then` – j4rey Sep 05 '20 at 06:21
  • then why should I use returneddata? cant't I do that with data also? That's not my point, I want to store data inside a local variable. – Babai Sep 05 '20 at 06:28
  • You have to wait the async `jsonData`. `console.log` seems to be executed before `returnedData` is set. – Vincenzo Manto Sep 05 '20 at 06:30
  • 2
    then use `async-await`, `let returnedData = await jsonData('./data2.txt')` – j4rey Sep 05 '20 at 06:30

2 Answers2

1

You can use a await, because your jsonData is asynchronous:

let returnedData = await jsonData('./data2.txt');
Vincenzo Manto
  • 886
  • 1
  • 11
  • 30
  • If I do that then I am getting an error , await is a reserved word – Babai Sep 05 '20 at 06:38
  • You `jsonData` is not async. Try to define it `async jsonData(file) {...}` Take a look at https://stackoverflow.com/questions/42299594/await-is-a-reserved-word-error-inside-async-function – Vincenzo Manto Sep 05 '20 at 06:47
0

You have to log inside the then block since Promises are asynchronous.

import { jsonData } from './fetchData.js';

let returnedData;
jsonData('./data2.txt')
.then((data) => {
    returnedData = data;
})
.then(() => console.log(returnedData));

Praveenkumar
  • 2,056
  • 1
  • 9
  • 18