javascript - 数组为空时未处理的 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 块。我该怎么做呢?
解决方案
推荐阅读
- java - 如何使用壁虎获取当前页面 URL?
- javascript - 使用 selenium 加载 href="#" 标签
- php - 使用列表函数的奇怪斐波那契结果
- python - python 套接字编程:制作 pim-join-prune 数据包
- linux - Perf 将一些直接跳转指令报告为内存访问指令
- django - 如何使用我自己的应用程序的内置管理登录面板登录用户?
- cakephp - Font Awesome 字形未显示为表单助手按钮标题
- php - 如何在 PHP 中永久类型转换类属性?
- node.js - 调用post方法时,密码对应时进入if语句,但我在if语句中的res被忽略,为什么?
- javascript - 下午 2 点启动了我的机器人,但机器人在 discord 上不在线