How can I export the data I received with then?

In such a case, because the process is asynchronous, I get the text undefined on the console. I can access this data by writing it externally to an array. But I think there is definitely another way. What should I do in such situations? Thanks advance for your answer.

class Request {
    get(url) {
        return new Promise((resolve, reject) => {
            fetch(url)
                .then(response => response.json())
                .then(data => resolve(data))
                .catch(error => reject(error))
        })
    }
}

const request = new Request()
let albums;
request.get("https://jsonplaceholder.typicode.com/albums")
    .then(data => {
        albums = data
    })
    .catch(error => console.log(error))

albums contains the array. What exactly are you wanting to do with the data in the array?

I want to pass the data to the albums variable without getting the undefined error

I do not get undefined when I run the following:

const request = new Request();
let albums;
request
  .get("https://jsonplaceholder.typicode.com/albums")
  .then((data) => {
    albums = data;
    console.log(albums);
  })
  .catch((error) => console.log(error));

The console.log shows the array of albums.

please, Try that

const request = new Request();
let albums;
request
  .get("https://jsonplaceholder.typicode.com/albums")
  .then((data) => {
    albums = data;
  })
  .catch((error) => console.log(error));
console.log(albums);

And just to be clear, this:

albums = data

does not “pass the data”. It creates a new variable that points to the same data.

How ı pass the data?

Randy is busy typing - I’ll let him answer.

albums will be undefined because the console.log statement does not wait until the value get method completes. You will need to do what ever you want inside the then's callback function. You could create a separate function to put whatever logic you want to apply to albums as the then method’s callback.

const processAlbums = data => {
 // do something with the data here
};

const request = new Request();
let albums;
request
  .get("https://jsonplaceholder.typicode.com/albums")
  .then(processAlbums)
  .catch((error) => console.log(error));
2 Likes

Okey I know thanks but I just want to learn, are there different methods? I would be glad if you can give examples of assign resources.

Yeah, dealing with asynchronous data is difficult. I’m sure every developer can remember being in your shoes and struggling with this. I would recommend spending some time doing some google searches on how to handle these things. Randy’s suggestion of doing what you need to do with the data inside the Promise is a common one. There are others like async/await. But really, it just takes practice.

If I get some time later, maybe I’ll do up a pen with some common strategies.

1 Like