My code:
export function function() {
let queryOptions = {
"suppressAuth": true, // Setting this option to true will bypass the permissions.
};
var itemsQueried = 0
var itemsProcessed = 0;
var itemsAmended = 0;
var itemsArray = [];
wixData.query('Notifications')
.ascending("_updatedDate")
.limit(1000)
.find(queryOptions)
.then(data => {
itemsQueried = data.items.length;
console.log("query result " + itemsQueried + " items");
data.items.forEach(function (item) {
itemsProcessed++;
var id = item._id;
var endpoint = item.title;
var latitude = item.latitude;
var longitude = item.longitude;
var range = item.range;
var email = item.email;
var initialNearbyHotspots = item.initialNearbyHotspots;
var usedCurrentLocation = item.usedCurrentLocation;
itemsArray.push(id);
getJSON(endpoint)
.then(json => json.data.length)
.then(length => {
if (length > initialNearbyHotspots) {
itemsAmended++;
var toUpdate = {
"_id": id,
"title": endpoint,
"latitude": latitude,
"longitude": longitude,
"range": range,
"email": email,
"initialNearbyHotspots": length,
"usedCurrentLocation": usedCurrentLocation
};
let updateOptions = {
"suppressAuth": true, // Setting this option to true will bypass the permissions.
};
wixData.update('Notifications', toUpdate, updateOptions)
.then(updatedItem => {
console.log(id + " completed " + initialNearbyHotspots + " to " + length);
sendEmail(updatedItem._id, latitude, longitude);
})
.catch(error => console.error(error))
} else {
var toUpdate = {
"_id": id,
"title": endpoint,
"latitude": latitude,
"longitude": longitude,
"range": range,
"email": email,
"initialNearbyHotspots": initialNearbyHotspots,
"usedCurrentLocation": usedCurrentLocation
};
let updateOptions = {
"suppressAuth": true, // Setting this option to true will bypass the permissions.
};
wixData.update('Notifications', toUpdate, updateOptions)
.then(updatedItem => {
console.log(id + "completed")
})
.catch(error => console.error(error))
}
})
.catch(error => console.error(error))
})
})
.finally(() => {
console.log("processed " + itemsProcessed + " items");
console.log("amended " + itemsAmended + " items");
console.log(itemsArray);
})
}
The itemsProcessed variable is incrementing as expected, however the itemsAmended variable is always returning 0 in console.log, irrespective of how many times the if (length > initialNearbyHotspots) condition is resolved as TRUE and should therefore be executing itemsAmended++
I would appreciate any pointers (and general advice as to optimisation, I find .then promises a bit unintuitive) - thanks in advance!