JS Async: 12. Promise method

by istiq20

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promise method</title>
</head>
<body>

<table>
    <tbody>
    <tr>
        <td>Id :</td>
        <td id="id"></td>
    </tr>
    <tr>
        <td>Name :</td>
        <td id="name"></td>
    </tr>
    <tr>
        <td>Price :</td>
        <td id="price"></td>
    </tr>
    </tbody>
</table>

<script>

    function getProduct() {
        return new Promise(function (resolve, reject) {

            const ajax = new XMLHttpRequest();
            ajax.open("GET", "api/product.json");
            ajax.onload = function () {
                if (ajax.status === 200) {
                    resolve(ajax.responseText);
                } else {
                    reject(`Error Get Product with response : ${ajax.status}`);
                }
            };
            ajax.send();

        });
    }

    getProduct()
        .then(function (response) {
            return JSON.parse(response);
        })
        .then(function (json) {
            document.getElementById("id").textContent = json.id;
            document.getElementById("name").textContent = json.name;
            document.getElementById("price").textContent = json.price;
        })
        .catch(function (error) {
            document.getElementById("id").textContent = error;
            document.getElementById("name").textContent = error;
            document.getElementById("price").textContent = error;
        })
        .finally(function () {
            console.info("Finally");
        })

</script>

</body>
</html>

JavaScript

// file: product.json
{
  "id": "1234",
  "name": "MacBook Pro 15",
  "price": 30000000
}