首页 > 解决方案 > 数组为空时未处理的 Promise Rejection 警告 Node js

问题描述

在以下代码中,obj1 和 obj2 是数组。

if(obj2.length != 0) {
    func(obj1, obj2);
}
//execute func only when obj2 is not empty

var func = (obj1, obj2) => {

const Channel = obj2.reduce((acc, curVal) => {
    obj1.forEach((item) => {
        if (curVal.Channel.includes('Name')) {
            item.dataarr.push({ 'MobileNo': curVal.mobnum})
        }
    })
    return obj1;
}, [])

};

但是当obj2为空时,我收到此错误:

(node:10837) UnhandledPromiseRejectionWarning: TypeError: obj2.reduce is not a function
    at func (/home/user/Desktop/serv.js:708:37)
    at breakdata (/home/user/Desktop/serv.js:720:5)
    at cached.getMulti.then (/home/user/Desktop/serv.js:643:7)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10837) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10837) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

从上面的错误中忽略这些行:

 at breakdata (/home/user/Desktop/serv.js:720:5)
 at cached.getMulti.then (/home/user/Desktop/serv.js:643:7)\

因为它们被抛出是因为 obj2.reduce 在抛出异常时没有给出任何输出。

我该如何处理: obj2.reduce is not a function当 obj2 数组为空时?我不希望这段代码抛出异常,因为生成的日志文件很大。我不知道如何在这里添加一个 catch 块。我该怎么做呢?

标签: javascriptnode.jsexception-handlingpromisetry-catch

解决方案


推荐阅读