1
我该如何同步运行一系列承诺,以便第二个承诺在第一个承诺完成之前不会执行?我在这里加载三个数据块,每个数据块有10个客户端,然后加载其余的数据块。这里的想法是继续前进,并显示其余的正在加载的前N个客户端。我不想要的是必须明确地说processChunk1()。然后(()=> processChunk2())等,就像我有下面。我希望它在一个循环中处理块,直到没有更多的客户端。任何帮助,将不胜感激!平展同步角度承诺
loadPerformanceDtos(): ng.IPromise<{}> {
var deferred = this.$q.defer();
var clientList: any = [];
$.extend(clientList, this.$location.search().client);
// If the user only searched for one client, we need to turn it into an array
if (!angular.isArray(clientList)) {
clientList = [clientList];
}
var that = this;
// Sort so we can chunk it
var sortedClients: string[] = (<string[]>clientList).sort();
const chunkSize: number = 10;
// Reset page's data
this.performanceDtoModels = [];
// Set up three chunks to load in order
var chunk1: string[] = sortedClients.splice(0, chunkSize);
var chunk2: string[] = sortedClients.splice(0, chunkSize);
var chunk3: string[] = sortedClients.splice(0, chunkSize);
// I don't want to have to explicitly define the groups below, I want this to be in a loop
processChunk(chunk1).then(() => {
// Resolve the inital page's progress bar
deferred.resolve();
processChunk(chunk2).then(() => {
processChunk(chunk3).then(() => {
processChunk(sortedClients);
});
});
});
function processChunk(chunk: string[]) {
var chunkDeferred = that.$q.defer();
if (chunk.length === 0) {
chunkDeferred.resolve();
} else {
that.performanceService.loadPerformanceData(chunk)
.success((data: IPerformanceDtoModel[]) => {
data.forEach((item: IPerformanceDtoModel) => {
// Add the final item to the page
that.performanceDtoModels.push(item);
});
chunkDeferred.resolve();
});
}
return chunkDeferred.promise;
}
return deferred.promise;
}
这正是我所需要的!我故意忽略了错误处理,并且可以自己处理。我只需要一些方向就可以使其具有通用性,因为我发现所有资源都希望您拥有已知数量的承诺链。 – user2339814