在使用猫鼬并创建自定义过滤器时,应该使用exec
的功能还是等待足够的时间?
这两种方式都会发挥作用
const locations = await Location.find(
{loc: $nearSphere: {
$geometry: {
type: 'Point',
coordinates: coordinates
}})
.exec(function (err, location) {
location = location.filter(async function(currentLocation){
return // Call google maps distance api for more accuracy
});
});
或
let locations = await Location.find(
{loc: $nearSphere: {
$geometry: {
type: 'Point',
coordinates: coordinates
}});
locations = locations.filter(async function(currentLocation){
return // Call google maps distance api for more accuracy
});
答案 0 :(得分:1)
在您的第一个示例中,分配const locations = await...
是多余的。
它没有任何作用,因为您正在.exec(function(err, location))
部分使用callback function返回查询结果。
第二个示例是使用promise based .find()
方法。
两个示例在猫鼬中均有效。您使用的是什么(回调或Promise)由您决定。 我个人更喜欢基于承诺的方法,因为当事情变得更加复杂时,它的可读性更高。错误处理也更容易。
此外,您还可以使用.find().then().catch()
语法。基本上与使用async/await
相同。