JS Async: 11. Promise
by istiq20
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Promise</title>
</head>
<body>
<script>
// Promise with Ajax
const promise = 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.responseText}`);
}
};
ajax.send();
});
console.info(promise)
</script>
</body>
</html>
JavaScript
// file: product.json
{
"id": "1234",
"name": "MacBook Pro 15",
"price": 30000000
}