在下面的代码中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数组为空时,如何处理obj2.reduce is not a function
?我不希望此代码引发异常,因为生成的日志文件很大。
我不知道如何在此处添加捕获块。我该怎么做?