JavaScript 如何将setTimeout()方法包装在一个Promise中
要将setTimeout包装在一个由未来返回的Promise中。我们可以使用then()方法将setTimeout包装在一个Promise中。then()方法最多接受两个参数,用于处理Promise的成功和失败条件的回调函数。该函数返回一个Promise。如果调用的函数onFulfilled,那么Promise就是已完成状态。如果调用的函数onRejected,那么Promise就是已拒绝状态。
语法:
Promise.then(onFulfilled, onRejected)
下面的示例将说明这种方法:
示例1: 在这个示例中,我们将看到使用Promise与then()块和setTimeout()方法的用法。
<!DOCTYPE html>
<html>
<head>
<title>
How to wrap setTimeout in a promise?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to wrap setTimeout in a promise?
</h3>
<br>
<button onclick="change()">
Click to print
</button>
<p id="gfg"></p>
<script>
function change() {
return new Promise(function (resolve, reject) {
// Setting 2000 ms time
setTimeout(resolve, 2000);
}).then(function () {
document.getElementById("gfg").innerHTML =
"Wrapped setTimeout after 2000ms";
});
}
</script>
</body>
</html>
输出结果:

示例2:
在这个示例中,我们将看到如何使用 Promises、async 函数和 setTimeOut() 方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to wrap setTimeout in a promise?
</h3>
<br>
<button onclick="resolvePromise()">
Click to print
</button>
<p id="gfg"></p>
<script>
let gfg = document.getElementById('gfg');
// function for promise example
async function resolvePromise() {
let newPromise =
new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Hello Geeks. Wrapped
setTimeout() in a promise");
}, 1000);
});
let result = await newPromise;
gfg.innerHTML = result;
}
</script>
</body>
</html>
输出:

参考: Promise.prototype.then() 方法
极客教程