I'm using async.js to call 3 asynchronous functions that run database queries and return their data in the results[]
parameter of the final function listed below:
async.series([
function(callback) {
datasetA.fetch(sqlQueryA).then(function(data) {
callback(null, data);
});
},
function(callback) {
datasetB.fetch(sqlQueryB).then(function(data) {
callback(null, data);
});
},
function(callback) {
datasetC.fetch(sqlQueryC).then(function(data) {
callback(null, data);
});
}
], function(error, results) {
// Results is array of data containing
// resultA, resultB, resultC.
});
I understand results from all three asynchronous functions are in the results[]
parameter. But what is the best way to identify the results from each query? I can think of three ways:
1. Ordinal - resultA will be at index 0, resultB at index 1, and resultC at index2. This is apparently implied in the async.js documentation, but not stated explicitly.
2. Modifying the callback parameter before calling async.js callback(null, data)
:
async.series([
function(callback) {
datasetA.fetch(sqlQuery).then(function(data) {
data['query'] = 'A';
callback(null, data);
});
},
function(callback) {
datasetB.fetch(sqlQuery).then(function(data) {
data['query'] = 'B';
callback(null, data);
});
},
function(callback) {
datasetC.fetch(sqlQuery).then(function(data) {
data['query'] = 'C';
callback(null, data);
});
}
], function(error, results) {
for (var i=0; i < results.length; i++) {
// results[i].query will be A, B or C.
}
});
3. Inspect the data to determine which query ran.
I don't like 3 because it tightly couples the database schema with code (I only included it for completeness). But I'm less certain about whether 1 or 2 is better. Since the async.js documentation only implies order of results mirrors the order of the asynchronous functions in the array, I'm leaning towards option 2.
Above all else. Why am I even having this problem. Perhaps I'm using the async.js library incorrectly?