Javascript 函数正在调用自身,而没有在其中实现任何递归调用
我有这个函数从mongodb获取商店Javascript 函数正在调用自身,而没有在其中实现任何递归调用,javascript,mongodb,node.js,Javascript,Mongodb,Node.js,我有这个函数从mongodb获取商店 exports.find_shops = function(selector, fields, limit, skip, cb){ if(typeof fields == 'function'){ limit = 0 cb = fields fields = {} skip = 0 } if(typeof limit == 'function'){ cb
exports.find_shops = function(selector, fields, limit, skip, cb){
if(typeof fields == 'function'){
limit = 0
cb = fields
fields = {}
skip = 0
}
if(typeof limit == 'function'){
cb = limit
limit = 0
skip = 0
}
if(typeof skip == 'function'){
cb = skip
skip = 0
}
if(typeof selector == 'string'){
limit = 1
selector = {_id: new db.bson_serializer.ObjectID(selector)}
}
console.log('a')
Shop.find(selector, fields).limit(limit).toArray(function(err, shops){
console.log('b')
if(err){
throw new Error(err)
} else {
if(limit == 1){
cb(shops[0])
} else {
cb(shops)
}
}
})
}
我在控制台中得到的输出如下
a
B
b
而我希望是这样
a
b
这里怎么了
编辑:
大概是
toArray()
函数将其输入转换为数组,然后将数组的每个元素传递给其参数中的闭包函数
如果是这种情况,那么您看到的结果可能只是由
toArray()
生成一个包含两个项的数组引起的。这不需要任何递归方式。您在没有进一步上下文的情况下抛出一些代码,希望我们能够理解它并找到解决方案?为什么不包括调用此函数的极其重要的代码?您好,我很抱歉没有在前面添加被调用方。这与我在其他两个地方使用的语法相同,toArray函数在这两个地方按预期工作。
exports.search = function(products, location, skip, cb){
if(typeof skip == 'function'){
cb = skip
skip = 0
}
this.find_shops({
products: {
$in: products
},
$or: [{
location: { $near: location , $maxDistance: 2 }
},
{
delivery: -1
},
{
delivery: {$lt: 2}
}]
}, {name: 1, location: 1, delivery: 1, products: 1}, 10, skip, function(shops){
shops.forEach(function(i,shop){
shops[i] = _.intersect(shop.products, products)
})
// now we have the products that user needs from this shop.
var combos = []
shops.forEach(function(i,shop1){
var combo = [i]
var p = shop1.products
shops.forEach(function(j,shop2){
if(i > j){
return
} else {
var newprod = _.intersect(p,shop2.products)
if(newprod.length == shop2.products.length){
return
} else {
p.push(shop2.products)
p = _.uniq
combo.push(j)
if(p.length == products.length){
combos.push(combo)
}
}
}
})
})
cb(combos)
})
}