函数返回undefined而不是bool

时间:2015-10-12 22:29:14

标签: javascript node.js mongodb mongoose

可能在这里遗漏了一些简单的东西但是对于我的生活无法理解为什么下面的函数返回undefined。

  var isOrphanEan = function isOrphanEan (ean) {

    Products.findOne({
      'ean': ean
    }, function (err, product) {
        return product.orphan;
    });
  }

  isOrphanEan(12345); //returns undefined

产品示例

{ 
_id: 55ad6b442afbebe82d077a04,
  orphan: true
  }

编辑:

console.logging产品返回:

{ _id: 55ad6b442afbebe82d077a04,
  ean: 4006643097328,
  aw_product_id: 3295182687,
  product_name: 'Multipower Shaker Neutral',
  product_brand: 'Multipower UK',
  product_description: '',
  img_sml: 'http://images.productserve.com/noimage.gif',
  img_lrg: '',
  rating: '',
  merchant_id: 2926,
  price_current: 'GBP4.99',
  price_rrp: '',
  aff_link: 'http://www.awin1.com/pclick.php?p=3295182687&a=234945&m=2926',
  direct_link: 'http://www.multipower.com/uk/product/multipower-shaker-09732/neutral',
  merchant_product_id: '09732',
  aw_image_url: '',
  orphan: true,
  created_at: Mon Jul 20 2015 22:42:28 GMT+0100 (BST),
  updated_at: Thu Oct 08 2015 23:20:35 GMT+0100 (BST),
  __v: 0 }

2 个答案:

答案 0 :(得分:1)

使用callbacks approach来处理异步响应:

var isOrphanEan = function isOrphanEan (ean, cb) {

    Products.findOne({
      'ean': ean
    }, cb);
}

  isOrphanEan(12345, function(err, product) {
     console.log(product.orphan);  
  });

答案 1 :(得分:-1)

您正在使用回调。函数isOrphanEan()不返回任何内容,而findOne()将在数据可用时调用回调。您需要在未命名的回调中处理product.orphan。

相关问题