I am using fetch api for fetching an URL that might return:
Response : status = 200, json body = {\'user\': \'abc\', \'id\': 1}
Here's slightly different approach: With a one-liner I create a response-like promise with ok, status and json-as-object (not a promise), then I decide what to do with this object. Generally I reject with response if response.ok is false, otherwise I resolve with only the json-data. Network errors/json-parse-errors are rejected as usual.
fetch(url, options)
.then(r => r.json().then(json => ({ok: r.ok, status: r.status, json})))
.then( r => r.ok ? r.json: Promise.reject(r))
response.json() returns an asynchronous result. You are not returning the object at parseJSON from within .then() chained to response.json(). To correct that issue you can return response.json() promise at parseJSON call and return object containing data and status from within .then() chained to response.json()
function parseJSON(response) {
return response.json().then(json => {
return {
data: json,
status: response.status
}
})
}