2018-02-09 01:51:48 +00:00
|
|
|
// Hit both the cache and the network, setting state for the cached version first,
|
|
|
|
// then the network version (as it's assumed to be fresher). Also update the db afterwards.
|
2018-02-09 06:29:29 +00:00
|
|
|
export async function cacheFirstUpdateAfter (networkFetcher, dbFetcher, dbUpdater, stateSetter) {
|
2018-02-09 01:51:48 +00:00
|
|
|
let networkPromise = networkFetcher() // kick off network request immediately
|
|
|
|
let dbResponse
|
|
|
|
try {
|
|
|
|
dbResponse = await dbFetcher()
|
|
|
|
stateSetter(dbResponse)
|
|
|
|
} finally {
|
|
|
|
let fetchAndUpdatePromise = networkPromise.then(networkResponse => {
|
|
|
|
/* no await */ dbUpdater(networkResponse)
|
|
|
|
stateSetter(networkResponse)
|
|
|
|
})
|
|
|
|
if (!dbResponse) { // no cached result available, await the network
|
|
|
|
await fetchAndUpdatePromise
|
|
|
|
}
|
|
|
|
}
|
2018-02-09 06:29:29 +00:00
|
|
|
}
|