首页 > 解决方案 > 从 EventEmiter 解决或拒绝后如何使代码停止运行

问题描述

我试图制作一个下载器,但现在我正在努力下载删除。我的概念很简单。删除文件,如果有,请停止下载过程。download-removed我目前的问题是尽管我返回被拒绝,但在收到事件后代码仍在继续。

这是针对 Node.js 的,我不使用这样的外部模块bluebird,因此请尽可能提供纯 JavaScript 代码。

function download(id) {
    return new Promise(async (resolve, reject) => {
      // some logics to define both *links* and *size*
      process.on("download-removed", ($id) => {
        console.log("removed")
        if (id === $id) {
          console.log("matched")
          return reject("download-removed");
        }
        console.log("unmatched")
      });
      // from here, when event received, code should be stop as reject returned
      for (let index in links) {
        console.log("start", (index, size - links.length + Number(index) + 1));
        this._current = path.join(this._directory, String(id), `${(index, size - links.length + Number(index) + 1)}.${/\.([a-zA-Z]+)(\.webp)*$/.exec(links[index])[1]}`);
        await global.toolkits.download(links[index], this._current, false, `https://my_website/${String(id)}.html`).then((response) => {
          this._current = null;
          switch (response) {
            case "downloaded":
            case "file-exist": {
              console.log("end");
              let copy = [...links];
              copy.splice(0, index);
              process.emit("download-progress", id, (index, size - links.length + Number(index) + 1), size);
            }
          }
        });
      }
      this._current = null;

      if (this._process.length) {
        this.download(this._process[0]);
        this._process.splice(0, 1);
      }
      console.log("return", id);
      return resolve("downloaded");
      // to here!
    });

  remove(id) {
    process.emit("download-removed", id);
    // eslint-disable-next-line no-unused-vars
    this._process = this._process.filter((value, index, array) => { return value !== id; });
    fs.rmdirSync(path.join(this._directory, String(id)), { recursive: true });
  }

标签: node.js

解决方案


在您的情况下,有一些可能的解决方案: 1. 在单独的线程进程
中运行下载过程,并在事件 2 上终止进程。创建一些全局变量,例如并在每个加载步骤之前验证它的状态(当您遍历链接时)。在系统事件中,切换到并退出加载脚本。
let DOWNLOAD_ALLOWED = trueDOWNLOAD_ALLOWEDfalse


推荐阅读