The function JobRequest.findByJobId
is carried out asynchronously. In JavaScript, it is not possible to block asynchronous operations, so you will need to manually synchronize them by counting. Here is a basic example (error handling has been omitted to keep it concise):
var results = [];
var pendingJobCount = ids.length;
_.forEach(ids, function(id) {
JobRequest.findByJobId(id, function(err, result) {
results.push(result);
if (--pendingJobCount === 0) callback(null, results);
});
});
Although there are wrapper constructs available to handle such scenarios, I prefer to explain the process straightforwardly. You can refer to dfsq's answer for more information on one of those wrappers, known as promises.
It is important to note that asynchronous operations may finish in a different order. Therefore, the order of items in the results
array may not correspond with the order of items in the ids
array. If maintaining this connection is crucial, you will have to manage it manually, such as by storing the results in a map rather than an array:
var results = {};
var pendingJobCount = ids.length;
_.forEach(ids, function(id) {
JobRequest.findByJobId(id, function(err, result) {
results[id] = result;
if (--pendingJobCount === 0) callback(null, results);
});
});
This example assumes no duplicates exist in the ids
array. If duplicate keys are present, results will be overwritten.
Similar to the above scenario, error handling would involve including extra details in the result. See the following example:
results.push({id: id, error: null, value: result});