Service Worker 后台同步 - 拒绝承诺 - waitUntil 没有重试?

Service Worker Background Sync - On rejecting promise - there are no retries from the waitUntil?

我正在创建一个利用 IndexedDB 和服务人员的第一个离线博客平台。这里的想法是,如果用户离线并尝试发送 post - 在后台发送。这个项目是为了我的论文,我只看了一个星期左右的承诺 - 如果这是一个简单的错误,我们深表歉意!

根据我在 react/redux 中的操作,我正在成功发送同步事件。

下面是我的同步事件处理程序的代码

self.addEventListener('sync', function(event) {
  if (event.tag == 'send_post') {
    //const URL
    console.log('sync from SW - send post');
    //this should try again if promise is rejected
    event.waitUntil(
      openDatabase('Outbox').then( (db) => {
        return databaseGet('posts',db).then( (posts) => {
          return sendAllFromOutbox(posts)
        } )
      } )

    );
  }
});

下面是 openDatabase - (IndexedDB)

    function openDatabase(name) {
      return new Promise(function(resolve, reject) {
        var version = 10;
        var request = indexedDB.open(name, version);
        var db;
        request.onupgradeneeded = function(e) {
          db = e.target.result;
          e.target.transaction.onerror = reject;
        };
        request.onsuccess = function(e) {
          db = e.target.result;
          console.log('OPENED DATABASE');
          resolve(db);
        };
        request.onerror = reject;
      });
    }

下面是数据库Get

function databaseGet(type,db) {
  return new Promise(function(resolve, reject) {
    var transaction = db.transaction([type], 'readonly');
    var store = transaction.objectStore(type);
    var request = store.getAll();
    request.onsuccess = function(e) {
      var result = e.target.result;
      resolve(result);
    };
    request.onerror = reject;
  });
}

最后,下面是 sendAllFromOutbox

function sendAllFromOutbox(posts) {
  return fetch('https://stirapi.herokuapp.com/sendPost', {
    headers: {'Content-Type': 'application/json'},
    method: "POST",
    body: JSON.stringify(posts)
  })
  .then( (response) => {
    console.log('response from SW sendAllFromOutbox', response);
  } )
  .catch( (err) => {
    console.log('error from SW sendAllFromOutbox',err);
  } )
}

根据我的理解,如果 sendAllFromOutbox fails/rejects - 它应该被再次调用。但它似乎没有被调用 - 因此没有在后台发送。

如果您想查看我的存储库 - 就在这里 https://github.com/georgecook92/Stir

谢谢!

乔治

由浏览器决定何时重试失败的同步事件。此外,它不会无限重试,但你知道这是最后一次尝试 syncEvent.lastChance (spec).

查看上面的代码,databaseGet 期望 (type,db),但您将其称为 databaseGet('posts'),因此当您尝试访问 [=14] 的属性时会抛出错误=],这是未定义的。 Chrome 的开发工具应该显示这一点,尤其是 "break on caught errors".

The idea here is if the user is offline and trying to send a post - send it in the background

无论用户当前状态如何,最好使用后台同步。当然,navigator.onLine 会告诉您用户是否确实处于离线状态,但如果 onLine 为真,则用户仍然可能没有可靠的连接。