javascript - 在 request-native-promise [node.js] 中发现未处理的承诺拒绝?
问题描述
编辑:我已经开始使用常规请求库进行管道处理,这使得错误处理得很好。话虽如此,这让我唯一的问题是程序无法正确退出并需要手动终止的罕见情况。我相信这篇文章是我现在遇到的同样的问题。
我有一个程序可以从通过 JSON 文件获得的 url 下载图像。在大型请求(80 多张图像)上,我会在几个文件上遇到错误,例如 ETIMEDOUT 和 Socket hangup。
我试图弄清楚我需要在哪里捕获这些未处理的承诺错误,因为它们使我的程序无法正确退出,有时会迫使用户 Ctrl+C 终止程序。
request({ uri: url, json: true })
.then((data) => {
const fileArray = [];
data.posts.forEach((el) => {
if (!el.filepath) return;
fileArray.push(el.filepath);
});
return fileArray;
})
.then((arr) => {
arr.forEach(el => {
request.head(el, () => {
request({ url: el, encoding: null, forever: true })
.pipe(createWriteStream(el))
.on('close', () => { console.log('File Downloaded!'); })
.on('error', (e) => { console.log(e); });
});
});
})
.catch((error) => console.log(error));
第一个请求代码块应该是无关紧要的,因为错误是文件下载而不是请求 json 数据。.pipe() 附加了一个 .on 'error' 处理程序。据我所知, request.head() 不是“可以”的,并且在 try/catch 中围绕整个 forEach 循环也不起作用。
我不确定如何解决这些错误,但现在程序运行得很好,我只想确保我现在可以捕获任何错误以改善用户体验。
解决方案
我会将它推入一个 promise 数组,然后调用 promise.all。
var filesToProcess = [];
request({ uri: url, json: true })
.then((data) => {
const fileArray = [];
data.posts.forEach((el) => {
if (!el.filepath) return;
fileArray.push(el.filepath);
});
return fileArray;
})
.then((arr) => {
arr.forEach(el => {
var promise = new Promise(function(resolve, reject) {
request.head(el, () => {
request({ url: el, encoding: null, forever: true })
.pipe(createWriteStream(el))
.on('close', () => { resolve('File Downloaded!'); })
.on('error', (e) => { reject(e); });
});
filesToProcess.push(promise);
})
});
})
.catch((error) => console.log(error));
Promise.all(filesToProcess).then(values => {
//all of the promises successful
}).catch(err => {
//one of the promises failed
});
推荐阅读
- java - 尝试使用 Android 应用程序的 Java 代码在 Android 上运行 NMAP 进程时权限被拒绝
- javascript - 为什么 Node REPL 对表达式的评估取决于它是否分配给变量?
- c# - 路由属性不适用于 Web Api 中的 HttpPost(未找到 404)
- python - 通过python传输加密文件:InvalidToken错误
- python - Python Tkinter 类中的线程方法
- javascript - 当元素存在时对元素做出反应
- c++ - 错误错误 C2872:“布尔”:kinect.h 的符号不明确
- reactjs - 为什么更新状态中的一个对象同时更新两者?
- azure-cosmosdb - 使用 OFFSET 和 LIMIT 的 Cosmos DB 分页性能
- r - if (min(gf) >= 0) {: 单倍型频率函数代码的最大似然估计中需要 TRUE/FALSE 的缺失值