Promise를 사용하면 Promise가 생성될 때 사전에 값을 알 수 없는 비동기 작업을 수행할 수 있습니다. Promise에는 세 가지 상태가 보류 중, 이행됨 및 거부될 수 있습니다.
다음은 JavaScript의 Promise 코드입니다 -
예
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JavaScript Promises<h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to display username using promises</h3>
<script>
let sampleEle = document.querySelector(".sample");
document.querySelector(".Btn").addEventListener("click", () => {
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((result) => {
result.forEach((element) => {
sampleEle.innerHTML += element.username + "<br>";
});
})
.catch((err) => alert(err));
});
</script>
</body>
</html> 출력
위의 코드는 다음과 같은 출력을 생성합니다 -

'여기를 클릭' 버튼을 클릭하면 -
