【问题标题】:Why can you not return an object to Javascript's Array.map() and it map it properly?为什么不能将对象返回给 Javascript Array.map() 并正确映射它?
【发布时间】:2013-06-15 09:32:02
【问题描述】:

我在下面有两个函数(它们是从一个较大的脚本中取出的,所以假设所有内容都已定义等等。self.sentenceObjs 工作得很好。它返回一个完全像它应该做的对象。self.parseBodySections 出于某种原因设置了@987654323 @ 到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;
    });
  };

【问题讨论】:

  • waterfall 返回什么?我对这个库不是很熟悉,但是通过阅读文档,它似乎实际上并没有返回函数的复合,而是将它暴露在回调中。你能检查console.log(async.waterfall([... 看看它输出了什么吗?
  • 请发布一个简短的、独立的示例来演示该问题。
  • @elclanrs 是的,我认为这与它有关,因为它返回 undefined。我自己对图书馆很陌生,所以我可能误解了一些东西。
  • 我认为你只需要运行parseBodySections inside waterfall 的回调,而不是相反,因为waterfall 是异步部分。我可能错了...
  • @elclanrs 是的,听起来它可能会解决问题。感谢您的尝试!

标签: javascript arrays json node.js map


【解决方案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);
  });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多