Skip to content

Instantly share code, notes, and snippets.

@smokinjoe
Created April 12, 2015 04:34
Show Gist options
  • Save smokinjoe/8979111dd90b2f2d0bd5 to your computer and use it in GitHub Desktop.
Save smokinjoe/8979111dd90b2f2d0bd5 to your computer and use it in GitHub Desktop.
Amazing example of async waterfall and map for cheating in nested result queries
// Use waterfall so that you can easily disconnect at the end of your code.
// It also makes node.js callbacks less confusing.
async.waterfall([
function (wCb) {
connection.connect();
// wCB is a callback function. Call it when you want to move to the
// next function in the waterfall
wCb();
},
function (wCB) {
connection.query('SELECT id, name FROM pages', function(err, pages, fields) {
if (err) {
// If you pass a first parameter in wCB, it will move to the
// last function of the waterfall and treat that as an error.
return wCB(err);
} else {
// Optionally, you can pass a second, third, etc. parameter
// which is carried over to the next waterfall function.
wCB(null, pages);
}
});
},
function (pages, wCB) { // Notice that the first parameter is not wCB!
// async.map lets us apply a function to a collection.
async.map(pages, function (page, mCB) {
// We can query to simulate a "join" and add it as a property of our object.
// Since the object is referenced, anything that we write on the object
// will be reflected outside the async.map.
connection.query(
'SELECT id, name FROM sections WHERE page_id = ?',
page.id,
function(err, sections, fields) {
if (err) return mCB(err);
page.sections = sections;
mCB();
}
);
}, function (err) {
// Finally, we invoke our callback function to move to the
// next waterfall function. Since there's none, it will go
// to the "ending" function.
if (err) {
wCB(err);
} else {
// We can still pass a parameter as usual.
wCB(null, pages);
}
});
}
], function (err, pages) {
// Unlike the normal waterfall functions, this has a different signature with "err" always first
if (err) throw err;
// We can now close our mysql connection
connection.end();
console.log(pages);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment