Skip to content

Instantly share code, notes, and snippets.

@JedWatson
Forked from getify/gist:8459026
Last active January 3, 2016 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JedWatson/8475422 to your computer and use it in GitHub Desktop.
Save JedWatson/8475422 to your computer and use it in GitHub Desktop.
Comparison between (my) old callback-structured code, @getify's asynquence refactor, and my async refactor
var doQuery = function() {
// passing an object to async.parallel will cause it to collect their results
// and provide them to the callback in an object with the same keys.
async.parallel({
// functions are passed a callback with the standard argument pattern of fn(err, result)
count: count.exec,
query: query.exec
}, function(err, results) {
// if either method returns a truthy err argument, the main callback is
// executed immediately and passed the error. send it on and exit.
if (err) return sendError('database error', err);
// transform the data and send it via `sendResponse()`
sendResponse({
total: results.count,
items: results.query.map(function(i) {
return {
name: req.list.getDocumentName(i, true) || '(' + i.id + ')',
id: i.id
};
})
});
});
}
var doQuery = function() {
// fetch total
return ASQ(function(done){
count.exec(function(err, total) {
// note: `return` here does nothing for asynquence, only
// exits the function early. :)
if (err) return done.fail('database error', err);
done(total); // pass along `total` as a value-message
});
})
// fetch items
.then(function(done, total){
query.exec(function(err, items) {
// note: `return` here does nothing for asynquence, only
// exits the function early. :)
if (err) return done.fail('database error', err);
done(total,items); // pass along both as value-messages
})
})
// transform the data to prepare it for `sendResponse()`
.val(function(total, items){
return {
total: total,
items: items.map(function(i) {
return {
name: req.list.getDocumentName(i, true) || '(' + i.id + ')',
id: i.id
};
})
};
})
// now, send the transformed data along
.val(sendResponse)
// handle any errors that propagate up to here
.or(sendError);
}
var doQuery = function() {
count.exec(function(err, total) {
if (err) return sendError('database error', err);
query.exec(function(err, items) {
if (err) return sendError('database error', err);
sendResponse({
total: total,
items: items.map(function(i) {
return {
name: req.list.getDocumentName(i, true) || '(' + i.id + ')',
id: i.id
};
})
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment