Search code examples
javascriptpromisefetch-api

Meaning of .then((resolve) => resolve.json())


Sorry for the basic question, I am very new to promises etc. Just wondering what the meaning of the 3rd line is?

window.onload = (function(){
    fetch('http://localhost:8080/CarSales/rest/cars')
    .then((resolve) => resolve.json())
    .then((data) => {
        var output = '';
        data.forEach(function(cars){
            output += '<tr><td>'+cars.make+'</td><td>'
            +cars.model+'</td><td>'+cars.year+'</td><td>'
            +cars.engine+'</td></tr>';
        });
        document.getElementById('table-body').innerHTML = output;
    })
})

Solution

  • .then((resolve) => resolve.json())

    The fetch api returns a response, but in order to parse a json response, you need to call the json function. This also returns a promise that finally returns the json data.

    So, this line is doing the resolve to json.