Last active
August 29, 2015 13:56
-
-
Save PistachioPony/9094998 to your computer and use it in GitHub Desktop.
How to pass information from function to function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Once you get to next(); it moves on to the next function and lets go of whatever information was captured there. | |
// for instance mariaItem finds the item with that particular _id and when it hits the next(); that information is gone... | |
// UNLESS | |
// You add a req.contents = {}; with that you are adding to the request hash a contents key and {} value. | |
// It always will pass the req, res, option for next. | |
// Next you add a result key with a result value. (The result value holds the the work of findOne). | |
// So that information is now stored in the res hash and when the computer goes to next function it takes that info with it. | |
var mariaItem = function (req, res, next) { | |
Item.findOne({ _id: "5099803df3f4948bd2f98391"}, function (err, result){ | |
req.contents = {}; | |
req.contents.result = result; | |
next(); | |
}); | |
}; | |
// The function below gets another item fro the DB and adds the result to the req hash as it did above, | |
// this time the key is called 'bananas'...inside toe contents hash... | |
// Now you ask it to display req.contents in json by calling res.json(req.contents) | |
// The req.contents contains the first functions findOne and the second functions findOne, shown when you hit /maria/item route. // so we are rendering a contents hash with two key value pairs. | |
var mariaTwo = function (req, res, next) { | |
Item.findOne({_id: "5099803df3f4948bd2f98392"}, function (err, result){ | |
req.contents.bananas = result; | |
res.json(req.contents); | |
}); | |
}; | |
app.get('/maria/item', | |
mariaItem, | |
mariaTwo | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment