我有一个从 IndexedDB 返回对象数组的承诺:
const syncData = () => {
return new Promise((resolve, reject)=>{
var all_form_obj = [];
var db = self.indexedDB.open('Test');
db.onsuccess = function(event) {
var db = this.result
// Table new_form
var count_object_store_new_form = this.result.transaction("new_form").objectStore("new_form").count()
count_object_store_new_form.onsuccess = function(event) {
if(count_object_store_new_form.result > 0){
db.transaction("new_form").objectStore("new_form").getAll().onsuccess = function(event) {
var old_form_arr = event.target.result
for(element in old_form_arr){
all_form_obj.push(old_form_arr[element])
}
}
}
}
// Table old_form
var count_object_store_old_form = this.result.transaction("old_form").objectStore("old_form").count()
count_object_store_old_form.onsuccess = function(event) {
if(count_object_store_old_form.result > 0){
db.transaction("old_form").objectStore("old_form").getAll().onsuccess = function(event) {
var old_form_arr = event.target.result
for(element in old_form_arr){
all_form_obj.push(old_form_arr[element])
}
}
}
}
}
db.onerror = function(err) {
reject(err);
}
resolve(all_form_obj)
})
};
解析数组后,我在同步事件中调用承诺:
self.addEventListener('sync', function(event) {
if (event.tag == 'sync_event') {
event.waitUntil(
syncData()
.then((form_arr)=>{
console.log(form_arr)
for(form in form_arr) {
console.log(form_arr)
}
}).catch((err) => console.log(err))
);
}
});
在我的承诺 syncData 的“then”中,我打印到控制台两次。
第一个 console.log 出现在控制台(我的对象数组)中,但第二个在循环中(for in)没有出现在控制台中,我不明白为什么。
我的目标是能够遍历每个对象并使用 fetch 将其发送到我的数据库,但问题是循环中的代码没有运行。