@yisrael-wix thank you. I’ve rebuilt my code using async/await and have split up my function into various logical sub-functions. The behaviour of my code is mostly as expected*, but I’m unsure how to implement an incremented variable in order to capture (by way of the console) how many times the if condition is resolved as true - where does this code need to sit?
*one thing I’m confused by is that console.log(“completed”) is executed early on, before the forEach loop has finished - why is this?
Thanks as always for any input.
export async function processAlerts() {
let queryResult = await queryItems();
await forEachItem(queryResult);
console.log("completed");
}
export async function queryItems() {
try {
const queryOptions = {
"suppressAuth": true,
};
const results = await wixData.query("Alerts")
.ascending("_updatedDate")
.limit(1000)
.eq("status", "active")
.find(queryOptions);
console.log(results);
return results.items;
} catch (error) {
console.error(error)
return error;
}
}
export async function forEachItem(arr) {
await arr.forEach(function (item) {
getJSONAtEndpoint(item);
})
}
export async function getJSONAtEndpoint(item) {
try {
let oldN = item.hotspotsInRange;
let endpoint = item.endpoint;
let json = await getJSON(endpoint);
let newN = json.data.length;
if (newN > oldN)
updateItemNewN(item, newN);
} else {
updateItemOldN(item);
}
} catch (error) {
console.error(error)
}
}
export async function updateItemNewN(item, newN) {
let toUpdate = {
"_id": item._id,
"endpoint": item.endpoint,
"lat": item.lat,
"lon": item.lon,
"range": item.range,
"email": item.email,
"firstName": item.firstName,
"lastName": item.lastName,
"hotspotsInRange": newN, //update hotspotsInRange with the value retrieved from getJSON
"usedCurrentLocation": item.usedCurrentLocation,
"contactId": item.contactId,
"status": "active"
};
const options = {
"suppressAuth": true,
};
let updatedItem = await wixData.update('Alerts', toUpdate, options);
sendAlertEmail(updatedItem.contactId, updatedItem._id, updatedItem.lat, updatedItem.lon, updatedItem.firstName);
}
export async function updateItemOldN(item) {
let toUpdate = {
"_id": item._id,
"endpoint": item.endpoint,
"lat": item.lat,
"lon": item.lon,
"range": item.range,
"email": item.email,
"firstName": item.firstName,
"lastName": item.lastName,
"hotspotsInRange": item.hotspotsInRange, //update hotspotsInRange with existing value
"usedCurrentLocation": item.usedCurrentLocation,
"contactId": item.contactId,
"status": "active"
};
const options = {
"suppressAuth": true,
};
await wixData.update('Alerts', toUpdate, options);
}