【问题标题】:function returning undefined instead of bool [duplicate]函数返回 undefined 而不是 bool [重复]
【发布时间】:2016-01-10 12:40:35
【问题描述】:

可能在这里遗漏了一些简单的东西,但我一生都无法弄清楚为什么下面的函数返回未定义。

  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 }

【问题讨论】:

  • 当你console.log(product) 时会发生什么?根据搜索条件,Products 可能没有找到任何项目。
  • 你没有返回任何东西,所以它返回 undefined。
  • ean 属性是否存储为整数?也许在搜索时尝试 ean.toString()。
  • 哦,@MinusFour 是对的。您需要在 isOrphanEan 中使用回调函数,因为 Products 正在异步获取您的项目。
  • isOrphanEan 应该接受一个在Product.findOne 完成时调用的回调,而不是返回一个值。

标签: javascript node.js mongodb mongoose


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用callbacks approach 处理异步响应:

    var isOrphanEan = function isOrphanEan (ean, cb) {
    
        Products.findOne({
          'ean': ean
        }, cb);
    }
    
      isOrphanEan(12345, function(err, product) {
         console.log(product.orphan);  
      });
    

    【讨论】:

      猜你喜欢
      • 2016-05-28
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2020-09-11
      • 2015-07-27
      • 2021-04-28
      相关资源
      最近更新 更多