【发布时间】:2015-09-09 15:14:14
【问题描述】:
我正在开发一项数据同步服务,该服务从 Web 服务中提取数据,然后将其存储在 IndexedDB 中。
我在我的 TypeScript Angular 服务中做这样的事情:
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) => {
});
我在控制台中收到一个post success,以及我预期的每个返回的record key。问题在于对我的DataService 的异步调用。 this.dataService.add 函数实际上是创建事务并将记录添加到 IndexedDb。
我的控制台中的输出(在 IndexedDB 的状态下 - 只有一条记录的键为 188)表明此代码示例仅在我的 @ 上调用了 add 函数987654329@ 表示records 中的最后一个元素。
控制台输出:
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
如何以不同的方式构建我的代码以使 for 循环“等待”每个异步调用完成?
【问题讨论】:
标签: javascript angularjs typescript indexeddb angular-promise