Main task of this function is to fetch device data array from a json file and mutate deviceLocation & upTime attributes in each child objects and return the mutated device array. Original deviceLocation property has values of longitudes & latitudes separated by Z. For example, 81.003Z6.764. This value will be split and sent to the reverseGeocode() async function that reverse geocode the coordinates using google map API and returns the result. calculateUpTime() function is just to convert seconds into days, hours, minutes & seconds.
Express route calls the getMainLocationsList() function. Then it calls the getLocationByDeviceName(deviceName) function which then finally calls the getDeviceData() function.
Issue happens when getDeviceData() function is getting executed to serve the above mentioned express request, if another identical request will be made. What I have found so far by debugging is that for loop index i is getting accessed and mutated by both events.
I want to avoid such multiple events from trying to access & mutate the index i concurrently.
const getDeviceData = async () => {
let deviceData = await JSON.parse(JSON.stringify(fetchDeviceData()));
for (let i = 0; i < deviceData.length; i++) {
const deviceLocation = deviceData[i].deviceLocation;
const [long, lat] = deviceLocation.split("Z");
const locationName = await reverseGeoCode(long, lat);
deviceData[i].deviceLocation = {
long: long,
lat: lat,
name: locationName,
};
outdoorDevices = deviceData[i].outdoorDevices;
for (let j = 0; j < outdoorDevices.length; j++) {
const deviceLocation = outdoorDevices[j].deviceLocation;
const [long, lat] = deviceLocation.split("Z");
const locationName = await reverseGeoCode(long, lat);
outdoorDevices[j].deviceLocation = {
long: long,
lat: lat,
name: locationName,
};
try {
outdoorDevices[j].upTime = calculateUpTime(
parseInt(outdoorDevices[j].upTime)
);
} catch {
outdoorDevices[j].upTime = "N/A";
}
}
}
return deviceData;
};