javascript - 是否有一种模式的名称,在该模式中,当新操作开始时,先前的异步操作会自动取消?

标签 javascript typescript asynchronous terminology cancellation

用户在上一个长时间运行的操作完成之前尝试做某事是很常见的。这可能会导致多个操作竞相改变应用程序状态。

一个简单的解决方案是取消除最后一个以外的所有操作。

它有名字吗?

我能找到的最接近的问题是关于 cancelling the previous action when a new action happens 的问题,但作者和答案都只谈实现。

redux-saga 有 takeLatest (在上面的问题中提到)它或多或少地做同样的事情,但在 saga 任务上运行。 “takeLatest”这个名称在其他地方似乎并不常见,也没有引用任何内容。

示例实现:

class AsyncActionSlot {
  // Cancellable promises used only to make this example simpler.
  private _promise: BluebirdPromise<string> | null = null;

  // Can be useful to check if the last process has
  // already finished running. Not used anywhere
  // else in this example.
  public get isBusy(): boolean {
    return this._promise !== null;
  }

  public cancel(): void {
    if (this._promise) {
      this._promise.cancel();
      this._promise = null;
    }
  }

  public do(promise: Promise<string>, callback: (msg: string) => void): void {
    this.cancel();

    this._promise = Bluebird.resolve(promise);
    this._promise.then((msg) => {
      this._promise = null;
      callback(msg);
    });
  }
}

示例用法:

const slot = new AsyncActionSlot();

// will be cancelled, won't print `'hello'`
slot.do(fetchHello(), console.log);

// will print `'world'`
slot.do(fetchWorld(), console.log);

最佳答案

我不知道是否有任何行业范围内的术语,但我只是将其视为“压倒一切”,例如在你的情况下,我可能会选择 AsyncOverridingActionSlot()(尽管这有点啰嗦)。

或者,现在回到字典,“取代”似乎是一个更合适的词,defined by the Cambridge Dictionary作为“替换某些东西,尤其是旧的或更老式的东西”。因此,您可以使用 AsyncSupersedingActionSlot() 之类的方法,或者将方法名称更改为 slot.supersedeDo()

关于javascript - 是否有一种模式的名称,在该模式中,当新操作开始时,先前的异步操作会自动取消?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445549/

相关文章:

javascript - 如何使用 Chrome 存储从对象中删除数据?

javascript - 使用 AJAX 按自定义分类术语过滤 WordPress 帖子

javascript - 专业的Node库是如何实现异步执行的?

javascript - Highcharts 中堆叠柱形图中的重叠和圆形堆叠

JavaScript 文本区域 : add line break

typescript - 如何在 Typescript 中使用导出?

javascript - 如何用另一个对象删除对象内部的键

javascript - TypeORM - 获取用户时永远不会从数据库返回密码

multithreading - 何时在 asio 中使用异步操作

ajax - jqplot 外部数据与异步调用?