node.js - 从 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 });
}
解决方案
推荐阅读
- c++ - 将不同类型的数据附加到字节向量
- c++ - 使用 C++ 替换嵌套字符串
- uwp - 如何在输入吐司通知uwp输入内容后触发按钮
- jenkins - 在 Jenkins 管道中,如何从脚本计算中设置参数值?
- r - 从向量的分组元素创建数据框
- iphone - ARKit – 检测相似但颜色不同的物体
- next.js - Next.js:自定义文档“_document”中“getInitialProps”方法中的访问请求(ctx.req)
- python - Django 中的 CreateView 单元测试
- javascript - 如何以编程方式检查用户是否允许我的应用在 Google Chrome 中“在此设备上存储文件”?
- windows - 在 Windows 控制台中配置 Kafka 控制台使用者时出现语法错误