.then((resolve) => resolve.json()) 的含义

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

抱歉这个基本问题,我对 promises 等很陌生。只是想知道第 3 行的含义是什么?

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;
    })
})

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

fetch api returns 一个响应,但是为了解析一个 json 响应,你需要调用 json 函数。这也是 returns 最终 returns json 数据的承诺。

因此,此行正在解析 json。

你正在解析 json,所以你实际在做什么,等待你的 JSON 数据将被转换为 js,然后你就可以使用数据了。