Search code examples
javascriptasynchronous

how do you handle a promise as JSON value after fetch?


I'm trying to fetch JSON data from a local asp.net core site, but where I expect the JSON to be it's a promise with the state fulfilled, and I don't know what to do with it.

When I debug I can see my value is in there, but if I try to get it from the JSON property I get undefined.

enter image description here

So the request in it self works I get no errors, I just don't know how to get the result.

The FetchAsync function:

static FetchAsync = async (url, body = {}, method = "get", credentials = "same-origin", mode = "same-origin") => await fetch(url, {
    method: method,
    headers: {
        "Content-Type": "application/json",
        "Accept": "application/json"
    },
    credentials: credentials.toLowerCase(),
    mode: mode.toLowerCase(),
    body: body && Object.keys(body).length > 0 ? JSON.stringify(WebRequestUtility.ProcessBodyData(body)) : null
}).then(response => {
    if (response.ok) {
        return new WebRequestResult(response);
    } else {
        throw new Error("Request failed: " + response.status + ". Status: " + response.statusText + ". URL: " + response.url);
    }
}).catch(error => {
    throw new Error("Request error: " + error.statusText);
});

The WebRequestResult class:

class WebRequestResult {
    constructor(response) {
        this.Response = response;
        this.Success = response.ok;
        this.Status = response.status;
        this.StatusText = response.statusText;
        this.Type = response.type;
        this.JSON = response.json();
    }

    get obj() {
        return JSON.parse(this.JSON);
    }
}

Solution

  • If you are struggling with line 10 on the image, it's because you cannot access the price value directly on response.JSON since it returns a promise.

    Use then and catch to get the price on the returned promise.

    response.JSON.then((res) => {
       document.getElementById("ShippingPrice").innerHTML = res.price; 
    })
    .catch((error) => {
       console.log(error);
    });