1

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...

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 Answer 1

6

Your "pullOut" function calls itself, but it throws away the result of that call.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What a plonker I am! Its blazing obvious now you point it out. Thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.