0

以下代码有什么问题?我在 mongo 中收集了水果、蔬菜和糖果。“testlist”包含包含食物的字符串,这些食物属于要在集合中查找的三个类别之一。

由于某种原因,convertedList 似乎从来没有由“糖果”组成,而只有水果和蔬菜。

var async = require("async"),
    testlist = ["Tomato", "Carrot", "Orange", "Chocolate"];

async.map(testlist, function (food, next) {
  async.parallel([function (done) {
    Fruit.findOne({"name": food}, done);
  },
  function (done) {
    Vegetables.findOne({"name": food}, done);
  },
  function (done) {
    // The line below appears to execute successfully but never end up in "convertedList"
    Candy.findOne({"name": food}, done);
  }
], function (err, foods) { 
         next(err, foods[0] || foods[1]);
      });
    },
    function (err, result) {

      var convertedList = [].concat(result);
      res.send(convertedList);
    });

为什么 Candy 没有被添加到生成的“convertedList”中?我该如何解决这个问题?

注意:我注意到,当我重新排列 Candy 和蔬菜的函数(完成)调用时,蔬菜似乎没有被添加到最终的转换列表中,但 Candy 确实如此。它似乎总是第三个函数(完成)被忽略以添加到 convertLIst 中。

4

2 回答 2

0

回调中的这一行async.parallel没有传递Candy查询的结果:

next(err, foods[0] || foods[1]);

试试这个:

next(err, foods[0] || foods[1] || foods[2]);
于 2013-05-08T02:04:20.150 回答
0

@JohhnyHK 是对的。除了怀疑您的查询返回的不是 null 之外,没有其他解释可以解释为什么 Candy 从未出现在您的列表中。

该测试通过(使用 mocha):

var async = require('async'),
  should = require('should'),
  sinon = require('sinon');


describe('async map', function () {
  var Fruit, Vegetables, Candy, service;
  var noop = function () {};

  beforeEach(function () {
    Fruit = sinon.stub({ findOne: noop });
    Vegetables = sinon.stub({ findOne: noop });
    Candy = sinon.stub({ findOne: noop });

  });


  it('should map', function (done) {

    var testlist = ["Tomato", "Carrot", "Orange", "Chocolate"];

    // return null record for everything
    Fruit.findOne.yields(null);
    Vegetables.findOne.yields(null);
    Candy.findOne.yields(null);

    // return some value when query matches (simulating mongo queries basically)
    Fruit.findOne.withArgs({name: 'Orange'}).yields(null, 'Orange');
    Vegetables.findOne.withArgs({name: 'Tomato'}).yields(null, 'Tomato');
    Vegetables.findOne.withArgs({name: 'Carrot'}).yields(null, 'Carrot');
    Candy.findOne.withArgs({name: 'Chocolate'}).yields(null, 'Chocolate');

    async.map(testlist, function (food, next) {
      async.parallel([function (done) {
        Fruit.findOne({
          "name": food
        }, done);
      },
          function (done) {
        Vegetables.findOne({
          "name": food
        }, done);
      },
          function (done) {
        // The line below appears to execute successfully but never end up in "convertedList"
        Candy.findOne({
          "name": food
        }, done);
      }
      ], function (err, foods) {
        next(err, foods[0] || foods[1] || foods[2]);
      });
    }, function (err, result) {

      var convertedList = [].concat(result);
      convertedList.should.eql(testlist);
      done();
    });

  });
});
于 2013-10-30T03:36:36.507 回答