我在 indexedDB 中保留离线发布的评论并与服务人员注册同步,但是一旦重新上线,除非我发布新评论,否则同步不会触发。经过一些研究,我认为这是由于 event.waitUntil 函数中的链式承诺而发生的。也许有人可以引导我朝着正确的方向前进:
self.addEventListener('sync', event => {
if (event.tag == 'outbox') {
event.waitUntil(
postReview()
).catch(err => {
if (event.lastChance) {
self.registration.showNotification('Failed');
}
throw err;
});
}
});
postReview = () => {
DBHelper.openDB()
.then(db => {
const tx = db.transaction(['outbox'], 'readonly');
const store = tx.objectStore('outbox');
return store.getAll();
})
.then(reviews => {
return Promise.all(
reviews.map(review => {
const formData = new FormData();
formData.append('restaurant_id', review.restaurant_id);
formData.append('name', review.name);
formData.append('rating', review.rating);
if (review.comments.value) {
formData.append('comments', review.comments);
}
return fetch(`${DBHelper.REVIEWS_URL}/`, {
method: 'POST',
body: formData
}).then(data => {
if (data) {
return DBHelper.openDB().then(db => {
const tx = db.transaction('outbox', 'readwrite');
const store = tx.objectStore('outbox');
return store.delete(review.id);
});
}
}).catch((err) => console.error(err));
})
);
});
};
在任何时候我都得到
Cannot read property 'catch' of undefined at self.addEventListener.event (sw.js:97)