我有这个代码:
this.array = [];
initArrayClicked() {
this.clearArr()
.then(this.addOneToArray.bind(this))
.then(this.addTwoToArray.bind(this));
}
我有一个按钮,当我点击它时,这个函数就会被调用,并且在这个 chian promise 的末尾 this.array
值是 [1, 2]
,没关系.
当我快速单击按钮两次并且最后的 this.array
每次都有不同的值时,问题就开始了([1, 2, 1, 2]
, [2, 1, 2]
)。
我希望当我单击按钮时,无论我单击按钮的速度有多快,我的最终结果都是 [1, 2]
。我想问题在于 promise 链没有完成,我从乞讨开始,这导致了不想要的结果。
我试图寻找解决方案,但找不到。
提前致谢,抱歉我的英语不好!
最佳答案
您可以将 click
处理程序设置为 null
,直到 Promise
链完成,然后将 click
处理程序重新附加到元素
let handleClick = () => {
button.onclick = null;
this.array = [];
this.clearArr()
.then(this.addOneToArray.bind(this))
.then(this.addTwoToArray.bind(this))
.then(() => button.onclick = handleClick.bind(this /* set `this` here */))
}
button.onclick = handleClick.bind(this /* set `this` here */);
关于javascript - 触发链 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45716319/