I have a function that posts various updates to the server using ajax. I need to let the user know once all of the updates have been sent to the server.
I have an array of promises then use promise.allSettled then but it seems to continue even though many of the promises are still pending.
$('#updateModal').modal('show');
console.log('Sending Updates To Server');
let DBOpenRequest = window.indexedDB.open('pending-updates');
var promises=[];
var recordsToDelete=[];
DBOpenRequest.onsuccess = function(event)
{
var db = event.target.result;
// db transaction
var itemUpdatePromises = [];
itemUpdatesTransaction = db.transaction('item-updates', 'readwrite'),
// get object store
itemUpdates = itemUpdatesTransaction.objectStore('item-updates'),
// get all records in object store
itemUpdatesRecords = itemUpdates.getAll();
itemUpdatesRecords.onsuccess = () =>
{
if (typeof itemUpdatesRecords.result!=='undefined')
{
if (itemUpdatesRecords.result.length>0)
{
recordsToDelete['itemUpdates']=itemUpdatesRecords.result;
console.log('Sending '+itemUpdatesRecords.result.length+' Item Updates To Server');
addElement('logWindow', '<p>Sending '+itemUpdatesRecords.result.length+' Item Updates To Server <i id="itemUpdateIcon" class="fa-duotone fa-paper-plane"></i></p>')
$.each(itemUpdatesRecords.result, function( index, value )
{
var promise = postItemUpdates(value);
promises.push(promise);
});
}
}
};
itemUpdatesRecords.onerror = () =>
{
//db.close;
console.log('Item Updates Object Store Not Found', itemUpdatesRecords.error);
};
The code above is building the promises array. But looking at the console output in the screenshot im getting the "all updates sent" log message before even "sending 2 item updates to server".
await delay(500); // this allowed the time for the promises array to populate before continuing - not an ideal solution but solved my issue.
console.log("before", promises.join(","))
Promise.allSettled(promises).then(function (values)
{
console.log("after", values.join(","));
const rejected = values.filter(result => result.status === 'rejected').map(result => result.reason);
if ((Array.isArray(rejected) && rejected.length > 0) || typeof rejected === 'undefined')
{
errorMsg('There Was A Problem Sending Updates To Server');
}
console.log('all updates sent')
The screenshot above is the console.log of the promises i am waiting to be resolved. The console.log(values) in the then function are empty and the success message fires straight away even though the promises are still pending. Does anyone know why the then function is firing before the promises are settled?