Javascript从嵌套函数中返回

时间:2015-08-11 13:45:19

标签: javascript node.js

我试图在路线中返回随机数发生器函数的输出...我一直在未定义' - 但不知道我做错了什么......

var randomizer = function() {
  // A load of stuff happens here.. and functions that are needed by the pullOut function (I've removed for brevity)
  var pullOut = function(pick) {

    if (playerList.length !== pick) {
      var random_item = getRandomItem(list, weight);

      if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
        playerList.push(random_item);
      }
      pullOut(pick);
    } else {
      console.log(playerList)
      return playerList;
    }
  }
  return pullOut(pick);
}


router.route('/ordercreated')
  .post(function(req, res) {

    var orderedItems = req.body.line_items;
    //  I foreach through all the items - calling the randomizer function on each one...
    _.forEach(orderedItems, function(n) {
      Pack.findOne({
        'product_id': n.variant_id
      }, function(err, pack) {
        if (err) {
          return res.send(err);
        }
        if (pack) {

          var list = [];
          var weight = [];

          _.forEach(pack.playerData, function(n) {
            list.push(n.name);
            weight.push(parseInt(n.chance));
          });


          console.log('randomizing', randomizer(pack.title, list, weight, n.qty, pack.pick));
        }
      });
    });

    res.sendStatus(200);

  })

1 个答案:

答案 0 :(得分:6)

你的" pullOut"函数调用自身,但它会抛弃该调用的结果。

var randomizer = function() {
  // A load of stuff happens here.. and functions that are needed by the 
  // pullOut function (I've removed for brevity)
    var pullOut = function(pick) {

      if (playerList.length !== pick) {
        var random_item = getRandomItem(list, weight);

        if (playerList.indexOf(random_item) == -1) { // doesn't exist. So add to array.
          playerList.push(random_item);
        }
        return pullOut(pick); // <--- add return
      } else {
        console.log(playerList)
        return playerList;
      }
    }
    return pullOut(pick);
}

如果没有return,当函数通过主if语句获取该路径时,它将返回undefined