【问题标题】:Javascript stopping an eventJavascript 停止事件
【发布时间】:2017-04-10 09:03:30
【问题描述】:

是否有可能停止一个事件并强制它结束?

string rows // Correctly formatted csv string.

csv
  .fromString(rows, { headers: false })
  .on('data', (data) => {
    if (condition) {
       // force to end.
    }
  }
  .on('end', () => cb(units));

因此,我希望尽早突破 csv 文件。

【问题讨论】:

  • 你使用的是什么 csv 库?
  • 如果 csv 库不能处理您需要的验证,那么您可以read the file line by line 并按照您认为合适的方式对其进行处理。我认为这同样适用于用户提供的字符串。
  • 但是如果问题是关于突然结束某些执行上下文,那么可以使用return 甚至throw

标签: javascript node.js csv events


【解决方案1】:

您似乎在使用node-csvtojson

我认为你可以停止发出这样的数据事件:

const converter = csv.fromString(rows, { headers: false })
converter.on('data', (data) => {
  if (condition) {
    converter.removeAllListeners('data');// where 'data' is the name of the event. If called without any arguments, all listeners added to csv converter will be removed
  }
}

来源:this thread on Github

【讨论】:

  • 你试过了吗?我尝试了上面的解决方案,它不起作用。文档中也没有提到上述关闭方法
  • 其实我没有测试,我只是看了这个thread。但我读得太快了,你显然必须使用removeAllListeners 而不是off
【解决方案2】:

这个呢?

const task = csv.fromString(rows, { headers: false })
task.on('data', (data) => {
  if (condition) {
    task.on('end', () => cb(units));
  }
}

【讨论】:

  • 我不会那样做。 'end' 回调应该在调用 'data' 之前存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 2011-07-04
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多