Fetch returns promise instead of actual data even after using 'then' [duplicate]
Asked Answered
O

1

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?

Oak answered 18/8, 2016 at 15:16 Comment(1)
Promises don't make anything synchronous, you can't get the value out. Use x.then(console.log)Buccaneer
M
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

Meathead answered 18/8, 2016 at 15:23 Comment(2)
Confirmed must transform and then pass this transform through to the next then pipe.Kopje
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: developer.mozilla.org/en-US/docs/Web/API/Body/json. After the first invocation the body gets locked.Breakup

© 2022 - 2024 — McMap. All rights reserved.