-1

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;
    })
})
CoJ265
  • 21
  • 4
  • `fetch()` doesn't return the response body synchronously, you need to use `.json()` (or `.text()`), that returns a new promise with that body. Here, you're chaining promises thanks to the `.then()` callback itself returning a promise (which is great), see how "flat" you code is? It helps fighting the "callback hell", the [Street Fighter style](https://i.pinimg.com/originals/41/d6/46/41d646a4b4ca17151c0a0ef6876859d5.jpg). – sp00m Apr 29 '20 at 08:52

2 Answers2

0

.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.

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

You're resolving json, so what you're actually doing, waiting when your JSON data, will be transalted to js and after that you are able to use data.

Rustam
  • 3
  • 3