代码之家  ›  专栏  ›  技术社区  ›  Blake

为什么服务工作者respondWith()可以返回一个fetch对象而不是一个真正的响应?

  •  0
  • Blake  · 技术社区  · 6 年前

    我在看MDN文档,弄不明白为什么 event.respondWith 可以有一个 fetch

    addEventListener('fetch', event => {
      // Prevent the default, and handle the request ourselves.
      event.respondWith(async function() {
        // Try to get the response from a cache.
        const cachedResponse = await caches.match(event.request);
        // Return it if we found one.
        if (cachedResponse) return cachedResponse;
        // If we didn't find a match in the cache, use the network.
        return fetch(event.request);
      }());
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Avin Kavish    6 年前

    实际的请求发起程序不需要响应。它期待着一个承诺,并最终成为一个回应。这个 MDN docs 准确地说:

    获取处理,并允许您为响应提供承诺 你自己。

    调用时不返回fetch对象 fetch(event.request) 您可以在此处返回任何决定响应的承诺,例如:

    return new Promise(function(resolve, reject) {
      setTimeout(function() { 
      resolve(/* { Fake Response Object } */);
      }, 1500);
    });