33

I am making a simple fetch call in my component, which looks like this

    var x = fetch(SOME_URL, SOME_POST_DATA)
             .then((response) => response.json())
             .then((responseJSON) => {return responseJSON});

    console.log(x);

The call executes successfully but the console prints a promise instead of data. What am I missing here?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Abhay Jain
  • 433
  • 2
  • 5
  • 11
  • 1
    Promises don't make anything synchronous, you can't get the value out. Use `x.then(console.log)` – Bergi Aug 18 '16 at 15:27

1 Answers1

48

The way promises works mean you'll need to handle the responseJSON inside the handler for then(). Due to the asynchronous nature of requests the outer code will already have returned by the time the promise resolves.

It can be hard to get your head around at first, but it's much the same as a "traditional" AJAX request - you handle the response in a callback.

To take your example:

var x = fetch(SOME_URL, SOME_POST_DATA)
    .then((response) => response.json())
    .then((responseJSON) => {
       // do stuff with responseJSON here...
       console.log(responseJSON);
    });

More reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

deceze
  • 510,633
  • 85
  • 743
  • 889
SimonR
  • 1,248
  • 9
  • 10
  • Confirmed must transform and then pass this transform through to the next then pipe. – Austin Witherow Sep 06 '17 at 12:16
  • 3
    be warned that you cannot call the `json()` method twice on the same response object, it will throw this error: `(TypeError): Failed to execute 'json' on 'Response': body stream is locked`. I ran into this problem when attempting to console.log the response. This does not work: `console.log(res.json()); return res.json()` This works: `const data = res.json(); console.log(data); return data`. The reason is `json()` reads the stream to completion: https://developer.mozilla.org/en-US/docs/Web/API/Body/json. After the first invocation the body gets locked. – JP Lew Jul 18 '19 at 21:16