javascript - 触发链 promise

标签 javascript angularjs promise angular-promise

我有这个代码:

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/

相关文章:

javascript - Twitter 列出小部件限制

javascript - Angularjs 绑定(bind)在注入(inject) html 时不起作用

javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误

javascript - 链式 promise 不会在拒绝时传递

javascript - 谷歌可视化柱形图对齐图例

javascript - 使用 javascript 和 php 将值插入数据库

javascript - 如何使用 jQuery/Javascript 检查用户是否已选中一组复选框中的至少一个复选框?

angularjs - Angular ui-grid 动态计算网格的高度

angularjs - 'IPromise<any >' is not assignable to type ' Promise<any>'

javascript - "A promise was created in a handler but was not returned from it"