首页 > 解决方案 > 在 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 循环也不起作用。

我不确定如何解决这些错误,但现在程序运行得很好,我只想确保我现在可以捕获任何错误以改善用户体验。

标签: javascriptnode.jserror-handlingpromiserequest

解决方案


我会将它推入一个 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
});

推荐阅读