gpt4 book ai didi

javascript promise 链不等待先前的 promise 执行

转载 作者:行者123 更新时间:2023-11-28 14:38:06 25 4
gpt4 key购买 nike

我正在努力理解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com