Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB.
In my TypeScript Angular Service, the code looks something like this:
this.http
.post(postUrl, postData)
.success((data: any, status, headers, config) => {
console.log("post success");
console.log("results:");
console.log(data);
var records = data.Records;
var promiseStack = [];
for (var i = 0; i < records.length; i++) {
var element = records[i];
var key = this.dataService.getKeyFromElement(objectStoreConfig, element);
console.log("key: " + key);
this.dataService.keyExists(objectStoreConfig, key).then((update) => {
if(update){
// TODO: put
promiseStack.push(true);
} else {
console.log("using dataService to add to objectStore...");
console.log("adding: " + key);
this.dataService.add(element, objectStoreConfig).then((result) => {
promiseStack.push(result);
});
}
});
}
this.q.all(promiseStack).then((result) => {
console.log("done adding/updating all.");
deferred.resolve(result);
});
})
.error((data, status, headers, config) => {
});
Upon running the code, I receive a post success
message in the console, along with the keys of each record as expected. However, the issue lies in the asynchronous calls to the DataService
. The problem arises specifically with the this.dataService.add
function responsible for creating transactions and adding records to IndexedDB.
After examining the console output and the state of IndexedDB, it appears that only one record with a key value of 188
is added using this code sample. This demonstrates that the add
function within DataService
is called only for the last element in the records array.
Console Log:
post success
results:
Object
key: 78
key: 194
key: 188
done adding/updating all.
using dataService to add to objectStore...
adding: 188
using dataService to add to objectStore...
adding: 188
using dataService to add to objectStore...
adding: 188
I'm currently exploring different ways to restructure my code so that the for loop allows each asynchronous call to be completed before proceeding to the next iteration. Any suggestions on how to achieve this?