我正试图在Angular中编写打字机效果,但在调用TypeWriter
:的组件中,我的承诺似乎没有得到正确解决
export class TypeWriter {
constructor(t, speed) {
this.content = t.innerHTML;
this.t = t;
this.typeSpeed = speed;
this.t.innerHTML = '';
}
private content: string;
private cursorPosition = 0;
private tag = '';
private writingTag = false;
private tagOpen = false;
private typeSpeed = 50;
private t;
public type(): Promise<void> {
return new Promise<void>((resolve) => {
if (this.cursorPosition >= this.content.length) {
console.log('done typewriter');
resolve();
}
if (this.content[this.cursorPosition]) {
// Typewriting logic
}
if (++this.cursorPosition <= this.content.length) {
setTimeout(() => {
this.type();
}, this.typeSpeed);
}
});
}
}
在组件中:
initTypewriter() {
const typewriter = document.querySelectorAll('[class*="typewriter"]');
if (!typewriter.length || typewriter.length == 0) { return; }
const typers: TypeWriter[] = [];
typewriter.forEach(t => {
typers.push(new TypeWriter(t, 50));
});
typers[0].type().then(() => { console.log('done tw0'); });
typers[1].type().then(() => { console.log('done tw1'); });
}
我想实现的是按顺序触发打字机。我知道reduce()
,也知道如何使用它,但我的问题是,type()
的承诺似乎从未得到解决。我的控制台输出:
done typewriter
done typewriter
但是,即使resolve()
显示之前的控制台日志,我也从未在控制台中输出done twX
。。。
我是不是遗漏了一些显而易见的东西?
每次在this.cursorPosition >= this.content.length
条件中都需要解决您的承诺
首先用promise包装setTimeout。
const setTimeoutProm = (delay) => new Promise(res => setTimeout(() => res(),delay))
然后将type()
方法更改为
public type(): Promise<void> {
return new Promise<void>((resolve) => {
if (this.cursorPosition >= this.content.length) {
console.log('done typewriter');
resolve();
}
if (this.content[this.cursorPosition]) {
// Typewriting logic
// maybe resolve()
}
if (++this.cursorPosition <= this.content.length) {
setTimeoutProm(this.typeSpeed).then(() => {
return this.type();
}).catch(err => { })
}
});
}