从服务工作者返回带有JSON的Response对象

时间:2018-07-30 14:51:28

标签: javascript promise service-worker indexeddb web-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解析为true(IndexedDB中的数据)时,前端得到一个空响应对象。就像我的响应对象是在IndexedDB Promise解析之前创建的。

1 个答案:

答案 0 :(得分:1)

无法运行代码有点猜测,但是

  • 我认为您需要等待localforage.iterate,因为它会返回一个 答应
  • 我认为您还需要等待localforage.setItem,因为 它也会返回一个承诺-使用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;