Is there a way to run a series of promises synchronously, ensuring that the second promise is not executed until the first one is completed? I need to load data in chunks of 10 clients each and display the first N clients while the rest are loading.
I want to avoid having to explicitly chain processChunk1().then(() => processChunk2()) as shown below. Instead, I am looking for a solution where the chunks can be processed in a loop until all clients are loaded. Any suggestions would be greatly appreciated!
loadPerformanceDtos(): ng.IPromise<{}> {
var deferred = this.$q.defer();
var clientList: any = [];
$.extend(clientList, this.$location.search().client);
// Convert single client search into an array
if (!angular.isArray(clientList)) {
clientList = [clientList];
}
var that = this;
var sortedClients: string[] = (<string[]>clientList).sort();
const chunkSize: number = 10;
this.performanceDtoModels = [];
var chunk1: string[] = sortedClients.splice(0, chunkSize);
var chunk2: string[] = sortedClients.splice(0, chunkSize);
var chunk3: string[] = sortedClients.splice(0, chunkSize);
processChunks([chunk1, chunk2, chunk3]).then(() => {
processChunks([sortedClients]);
});
function processChunks(chunks: string[][]) {
var chunkDeferred = that.$q.defer();
if (chunks.length === 0) {
chunkDeferred.resolve();
} else {
var chunk = chunks.shift();
that.performanceService.loadPerformanceData(chunk)
.success((data: IPerformanceDtoModel[]) => {
data.forEach((item: IPerformanceDtoModel) => {
that.performanceDtoModels.push(item);
});
chunkDeferred.resolve();
});
}
return chunkDeferred.promise;
}
return deferred.promise;
}