Created
December 3, 2015 05:50
-
-
Save Kudo/e23172920c07c6b8fa6e to your computer and use it in GitHub Desktop.
ES6 Promise try sequence (try cache first then network)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getSomething() { | |
let cachePromiseFn = () => { | |
return cacheStorage.getItem(CACHE_KEY) | |
.then(value => { | |
return value && JSON.parse(value); | |
}); | |
}; | |
let requestPromiseFn = () => { | |
return fetch('https://localhost/foo') | |
.then(response => response.json()) | |
.then(response => { | |
cacheStorage.setItem(CACHE_KEY, JSON.stringify(response)); | |
return response; | |
}); | |
}; | |
let promise = [cachePromiseFn, requestPromiseFn].reduce((currPromise, nextPromiseFn) => { | |
return currPromise.then(value => { | |
if (value == null) { | |
return nextPromiseFn(); | |
} else { | |
return value; | |
} | |
}); | |
}, Promise.resolve()); | |
promise | |
.then(value => { | |
console.log('We got something from either cache or network request', value) | |
return value; | |
}) | |
.catch(error => console.error('getSomething() error - ' + error)); | |
return promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment