I have the following api :
for (var index in workload.elements) {
(function(index) {
var arr = [];
var resourceIdentifiers = {};
var elementinfo = {};
var metadataModified = {};
elementinfo = workload.elements[index];
arr[index] = workload.elements[index].uri;
if (workload.elements[index].parameters.imageUri) {
arr.push(workload.elements[index].parameters.imageUri);
}
resourceIdentifiers = arr.join(',');
console.log('uri' + resourceIdentifiers);
mysql.elementlevelpricing(resourceIdentifiers, function(result) {
elementlevelpricingSummary = result;
metadataModified = workload.elements[index].metadata;
metadataModified.pricingsummary = elementlevelpricingSummary;
delete elementinfo.metadata;
elementinfo.metadata = metadataModified;
workloadinfo.elements = JSON.stringify(elementArray, null, 2);
elementArray[index] = elementinfo;
console.log(JSON.stringify(elementArray, null, 2));
res.send(JSON.stringify(elementArray, null, 2));
});
})(index);
}
console.log prints the correct result , but the response to the REST call is incorrect and getting the result of only one the value getting into the loop.
First off, use a forEach or map instead of a for loop with IIFEs.
Second, an HTTP request only has one response. You can't send multiple requests with res.send firing off a few times. If you want all of the information, just aggregate the results of JSON.stringify(elementArray, null, 2) and send the final aggregated data with res.send.