问题描述
我在快递上创建了一个实时搜索框,它显示了2个错误。
(1)TypeError(2)未处理的承诺拒绝
码:
router. post('/search-phrasing', async (req, res) => {
const {
phrasing
} = req.body;
const
phrasingArray = phrasing.trim().split(' ');
phrasingArray.map(async (phrasing) => {
let suggestions = [];
await Response.find({
entities: {
$regex: new RegExp(phrasing)
}
}).sort({
phrasing: 'asc'
}).then((data) => {
if (data[0]) {
suggestions.push({
id: data[0]._id,
phrasing: data[0].phrasing
});
res.send(suggestions);
}
}).catch((err) => console.log(err));
});
});
1楼
不要尝试以这种方式循环异步功能,因为这不是必需的,当然不要在循环中发送响应。
相反,您应该.map()正则表达式列表到 :
router.post('/search-phrasing', (req, res) => {
const { phrasing } = req.body;
if (phrasing == undefined || ( typeof(phrasing) != 'string' ) ) {
console.error("phrasing is required as a string");
return res.end(); // really should have better error handling
}
const phrasingArray = phrasing.trim().split(' ');
Response.find({ entities: { $in: phrasingArray.map(e => RegExp(e)) })
.sort('phrasing')
.select('phrasing')
.then(suggestions => res.send(suggestions))
.catch(err => console.error(err));
})
运算符接受要匹配的参数数组。 它也碰巧接受正则表达式作为那些参数。 它基本上是运算符的简写,但始终适用于一个字段。
否则,尝试执行此操作是对数据库执行多个语句,等待各种承诺,然后尝试从所有这些构建单个响应。 当已经有查询表达式已经处理了这一点时,这根本没有必要。
还要检查您的输入类型。 不要盲目假设您已将所需数据提供给POST正文。 检查它是否存在,如此处所示,否则会出现异常