从 service worker 返回带有 JSON 的 Response 对象

Returning Response object with JSON from service worker

我正在尝试挂钩某些 JSON 的提取请求,并在进入网络之前检查数据是否在 IndexedDB 中以获取它。我认为我的承诺没有解决,但发生了一些奇怪的事情。

这是我的代码:

event.respondWith(async function() {
        var data = {success:true, msg:'', data: []};

        localforage.iterate(function(value, key) {
            data.data.push([key, value])
        })
        if (data.data.length > 0) {
            return await new Response(JSON.stringify(data),{
                headers: { "Content-Type" : "application/json" }
            });
        }

        let response = await fetch(event.request)
        // clone response as it can only be used once and needs to be returned for client fetch
        let responseData = await response.clone().json()
        await responseData.data.forEach(function (todo) {
            localforage.setItem(todo[0], todo[1])
        })

        return response

    }())

但是,当 if 解析为真(IndexedDB 中的数据)时,我的前端得到一个空的响应对象。就好像我的响应对象是在 IndexedDB 承诺解决之前创建的。

无法 运行 代码但

有点猜测
  • 我认为你需要等待 localforage.iterate 因为它 returns 承诺
  • 我想你还需要等待 localforage.setItem 因为 它 returns 也是一个承诺 - 使用 Promise.allmap 应该可以为您处理

    var data = {success:true, msg:'', data: []};
    
    await localforage.iterate((value, key) => {
        data.data.push([key, value])
    })
    if (data.data.length > 0) {
        return new Response(JSON.stringify(data),{
            headers: { "Content-Type" : "application/json" }
        });
    }
    
    let response = await fetch(event.request)
    // clone response as it can only be used once and needs to be returned for client fetch
    let responseData = await response.clone().json()
    await Promise.all(responseData.data.map(todo => {
        return localforage.setItem(todo[0], todo[1]);
    }));
    
    return response;