简体   繁体   English

从嵌套函数内返回的Javascript

[英]Javascript Returning from within a nested function

I'm trying to return the output of the randomizer function within a route... I keep getting 'undefined' - but no idea what I'm doing wrong... 我正在尝试在路由中返回随机化器函数的输出...我一直在获取'undefined'-但不知道我在做什么错...

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);

  })

Your "pullOut" function calls itself, but it throws away the result of that call. 您的“ 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);
}

Without that return , when the function took that path through the main if statement it would return undefined . 如果没有该return ,则函数通过主if语句采用该路径时,它将返回undefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM