这是我个人用于查询可变数量的“类型”(导致单独的查询)的请求。我计算请求的类型数量,收集查询响应并在它们全部收集后立即触发回调:
/**
* @param payLoad - Object, expected to contain:
* @subparam type - Array, required.
* @subparam location - Array, contains [lat,lng], optional
* @subparam range - Int, optional
* @subparam start - String, optional
* @param cbFn - Function, callBack to call when ready collecting results.
*/
socket.on('map', function (payLoad, cbFn) {
if (typeof cbFn === 'undefined') cbFn = function (response) {};
var counter = 0,
totalTypes = 0,
resultSet = [];
if (typeof payLoad.type === 'undefined' || !(payLoad.type instanceof Array)) {
cbFn({error : "Required parameter 'command' was not set or was not an array"});
return;
}
totalTypes = payLoad.type.length;
/**
* MySQL returns the results in asynchronous callbacks, so in order to pass
* the results back to the client in one callBack we have to
* collect the results first and combine them, which is what this function does.
*
* @param data - Object with results to pass to the client.
*/
function processResults (data) {
counter++;
//Store the result untill we have all responses.
resultSet.push(data);
if (counter >= totalTypes) {
//We've collected all results. Pass them back to the client.
if (resultSet.length > 0) {
cbFn(resultSet);
} else {
cbFn({error : 'Your query did not yield any results. This should not happn.'});
}
}
}
//Process each type from the request.
payLoad.type.forEach(function (type) {
switch (type.toLowerCase()) {
case "type-a":
mysqlClient.query("SELECT super important stuff;",
function selectCallBack (err, results) {
if (!err && results.length > 0) {
processResults({type : 'type-a', error : false, data : results});
} else {
processResults({type : 'type-a', error : "No results found"});
}
});
break;
case "type-b":
mysqlClient.query('SELECT other stuff',
function selectCallBack (err, results) {
if (!err && results.length > 0) {
processResults({type : 'type-b', error : false, data : results});
} else {
processResults({type : 'type-b', error : "No results found"});
}
});
break;
default:
processResults({type : type, error : 'Unrecognized type parameter'});
break;
}
});
});