Ola Kozioł
Ola Kozioł

Reputation: 95

How to access date in next .then() - fetch api

I wonder if there is a way to access data from then on the next one? Code looks like this:

fetch(`http://localhost:3003/users/${userObject.id}`)
        .then(res => res.json())
        .then(user => {
          ...
        })
        .then(???) 

and in second then I have all the needed info about the user. When I put everything in second then it works, but code is very messy and repetitive and I would like to put some things into function. Unfortunately, in that case, I don't have access to some data...

Any ideas? Thanks!

Upvotes: 0

Views: 735

Answers (2)

decho
decho

Reputation: 895

but code is very messy and repetitive and I would like to put some things into function

Just use async/await syntax, it's much more understandable.

(async() => {
    const request = await fetch(`http://localhost:3003/users/${userObject.id}`);
    const result = await request.json();

    // proceed to do whatever you want with the object....
})();

This is a self-executing function, but you can also declare this in the following way:

const myFunc = async() => {
    const request = await fetch(`http://localhost:3003/users/${userObject.id}`);
    const result = await request.json();

    // your logic here or you can return the result object instead;
};

or even without arrow functions:

const myFunc = async function() {
    const request = await fetch(`http://localhost:3003/users/${userObject.id}`);
    const result = await request.json();
    console.log(result.id);
};

Upvotes: 1

TheMisir
TheMisir

Reputation: 4279

You can pass an argument to the next promise by returning it from the previous one.

fetch(`http://localhost:3003/users/${userObject.id}`)
        .then(res => res.json())
        .then(user => {
          return user.id;
        })
        .then(userId => {
          console.log('user id is:', userId);
        });

Also, you can accomplish same result by using async programming like bellow:

async function fetchSomeData() {
  var res = await fetch(`http://localhost:3003/users/${userObject.id}`);
  var user = await res.json();

  return user;
}

fetchSomeData().then(user => {
  console.log('user id is:', user.id)
});

Upvotes: 2

Related Questions