Created
October 19, 2013 14:58
-
-
Save mikekunze/7057021 to your computer and use it in GitHub Desktop.
We can do some fun stuff in Node.JS with asynchronous programming. With closures, we can pull a document collection from a NoSQL database, manipulate the results, and push it to an array stored via closure in the parent scope.
This file contains hidden or 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
require './nosql' | |
require 'async' | |
# new results array. this will be available via closure | |
results = [] | |
# Start the NoSQL connection | |
nosql.connect ()-> | |
# Get the collection pointer | |
collection = nosql.getCollection 'collection' | |
# Find the documents | |
collection.find {}, (documents)-> | |
# Create our iterator fn to be consumed by the async library | |
eachDocument = (doc, cb)-> | |
# Do something to doc; add/remove/modify variables. | |
# Push it to the results array that is in a | |
# parent scope and available via closure. | |
results.push doc | |
async.forEach documents, eachDocument, ()-> | |
# At this point, we have finished getting and dealing with documents. | |
# We can close the db and deal with the results. | |
nosql.close() | |
# If we were writing this in an express route, use res.send | |
res.send { success: true, results: results } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment