我试图理解 async 和 wait 关键字。我编写了一个简单的 HTML 文件和一个 JS 文件来演示它。
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise1 resolved");
}, 10000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise2 resolved");
}, 5000)
})
async function handlePromises() {
const result1 = await promise1;
console.log(result1);
const result2 = await promise2;
console.log(result2);
}
handlePromises();
// const myButton = document.getElementById("myButton");
// myButton.addEventListener("click", handlePromises);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width = device-width, initial-scale = 1.0">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<button id="myButton">Click me</button>
</body>
</html>
控制台显示两者
Promise1 resolved
Promised2 resolved
重新加载页面后 10 秒(这是预期的)但是如果我取消注释最后 2 行并注释 handlePromises()
函数并单击按钮,控制台会显示两者
Promise1 resolved
Promise2 resolved
5秒后。我认为它的行为方式与第一种情况相同。如果我再次单击按钮而不重新加载页面,控制台将打印
Promise1 resolved
Promise2 resolved
立即。为什么同一个函数在不同场景下表现不同。