Javascript从嵌套函数中返回

我试图返回一个路由中随机函数的输出…我不断收到'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); }) 

你的“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语句的path,它将返回undefined