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