1

我在下面有两个函数(它们是从一个更大的脚本中取出的,所以假设所有内容都已定义等等。self.sentenceObjs效果很好。它返回一个完全像它应该做的对象。self.parseBodySections出于某种原因,设置bodyJSON为一个数组,undefined即使self.sentenceObjs返回给定的完美对象我要映射的dom对象数组。由于某种原因,当我运行dom.map(self.sentenceObjs)它时,它会为每个对象返回未定义。知道为什么会这样吗?Array.map()我错过了什么吗?

  self.parseBodySections = function(dom, cb) {
    var bodyJSON = dom.map(self.sentenceObjs);
    console.log(bodyJSON); // prints: [ undefined, undefined, undefined, undefined, undefined ]

    return cb(null, bodyJSON);
  };

  self.sentenceObjs = function(section) {
    var paragraphToTextAndLinks = function(cb) {
      return self.paragraphToTextAndLinks(section.children, function(err, paragraphText, links) {
        if (err) {
          return cb(err);
        }

        return cb(null, paragraphText, links);
      });
    };

    return async.waterfall([
      paragraphToTextAndLinks,
      self.paragraphToSentences
    ],
    function(err, sentences, paragraphPlaintext) {
      var paragraph = {
        type: section.name,
        value: paragraphPlaintext,
        children: sentences
      };

      console.log(paragraph) // prints perfect object (too long to show here)

      return paragraph;
    });
  };
4

1 回答 1

1

问题是,您在瀑布的回调函数中返回“段落”。所以函数 sentenceObjs 什么也不返回,或者未定义。

您需要将回调函数传递给 sentenceObjs 并调用 async.map 而不是 Array.map:

self.parseBodySections = function(dom, cb) {
  async.map(dom, self.sentenceObjs, function(err, bodyJSON) {
    console.log(bodyJSON); // prints: [ undefined, undefined, undefined, undefined, undefined ]
    return cb(null, bodyJSON);
  });
};

self.sentenceObjs = function(section, cb) {
  var paragraphToTextAndLinks = function(cb) {
    return self.paragraphToTextAndLinks(section.children, function(err, paragraphText, links) {
      if (err) {
        return cb(err);
      }

      return cb(null, paragraphText, links);
    });
  };

  return async.waterfall([
    paragraphToTextAndLinks,
    self.paragraphToSentences
  ],
  function(err, sentences, paragraphPlaintext) {
    var paragraph = {
      type: section.name,
      value: paragraphPlaintext,
      children: sentences
    };

    console.log(paragraph); // prints perfect object (too long to show here)

    return cb(null, paragraph);
  });
};
于 2013-06-28T10:20:55.420 回答