- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力理解 JavaScript 的 promise 。我有一个简单的列表,我想通过添加一个“事件”类来依次突出显示每个元素,每个元素之间有一个暂停。
所以我有以下标记 -
<h2 class="step step1">Promise</h2>
<h2 class="step step2">Promise</h2>
<h2 class="step step3">Promise</h2>
<h2 class="step step4">Promise</h2>
和 2 个 JavaScript promise 。首先要设定步骤-
function setStep(step) {
return new Promise(function (resolve, reject) {
console.log("Step ", step, new Date())
document.querySelectorAll('.step').forEach(function (match) {
match.classList.remove("active");
});
document.querySelector(".step" + step).classList.add("active");
resolve(step);
})
}
第二个实现等待 -
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
然后我尝试像这样将它们链接在一起 -
wait(1000)
.then(function () { setStep(1) })
.then(wait(1000))
.then(function () { setStep(2) })
.then(wait(1000))
.then(function () { setStep(3) })
第一次等待似乎按预期执行,但其他所有事情似乎都一起发生,并且步骤 3 被突出显示,中间没有等待。控制台消息都显示相同的时间戳。
我忽略了什么?
完整代码如下-
<style>
.active {
background-color: #C00;
color: #FFF;
}
</style>
<h2 class="step step1">Step 1</h2>
<h2 class="step step2">Step 2</h2>
<h2 class="step step3">Step 3</h2>
<script>
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
function setStep(step) {
return new Promise(function (resolve, reject) {
console.log("Step ", step, new Date())
document.querySelectorAll('.step').forEach(function (match) {
match.classList.remove("active");
});
document.querySelector(".step" + step).classList.add("active");
resolve(step);
})
}
wait(1000)
.then(function () { setStep(1) })
.then(wait(1000))
.then(function () { setStep(2) })
.then(wait(1000))
.then(function () { setStep(3) })
</script>
最佳答案
您需要将函数引用传递给.then()
,而不是 promise 。所以改变这个:
.then(wait(1000))
对此:
.then(wait.bind(null, 1000))
或者这个:
.then(() => wait(1000))
.then()
仅当您向其传递稍后可以调用的函数引用时才能正常工作。当您执行 .then(wait(1000))
时,您将立即执行 wait(1000)
并将返回值( promise )传递给 .then ()
。这不是 .then()
的工作原理,您也不希望立即执行 wait(1000)
。
或者,您可以创建一个新的 waitFn()
,它返回一个可以按照您的方式使用的函数(因为它在调用时返回一个函数):
function waitFn(t) {
return function() { return wait(t);}
}
然后,你可以这样做:
wait(1000)
.then(function () { setStep(1) })
.then(waitFn(1000))
.then(function () { setStep(2) })
.then(waitFn(1000))
. then(function () { setStep(3) })
关于javascript promise 链不等待先前的 promise 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49207086/
我的应用将 SceneKit 内容的“页面”与图像和文本交替。当我从图像页面前进到新的 SceneKit 页面时,前一个 SceneKit 页面中的内容会短暂显示,然后被新内容替换。时髦。 我只使用一
我正在尝试处理(在 C# 中)包含一些数字数据的大型数据文件。给定一个整数数组,如何对其进行拆分/分组,以便如果下一个 n(两个或更多)是负数,则前一个 n 元素被分组。例如,在下面的数组中,应该使用
刚接触promises,研究过。所以我的代码和我的理解: sql.connect(config).then(function(connection) { return connection.req
目前我在 if (roobaf) block 中有一些代码,这取决于 foo 和 bar 是否为假。我可以在 block 内再次检查这些条件,但感觉像是不必要的代码重复。 if (foo) {
我是一名优秀的程序员,十分优秀!