我试图挂接到某些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解析之前创建的。
答案 0 :(得分:1)
无法运行代码有点猜测,但是
localforage.iterate
,因为它会返回一个
答应我认为您还需要等待localforage.setItem
,因为
它也会返回一个承诺-使用Promise.all
和map
应该为您处理承诺
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;