chore: Tidy up promise handling and testing

This commit is contained in:
Bouncey
2018-12-03 10:33:07 +00:00
committed by mrugesh mohapatra
parent f66e59e20c
commit a1f64f4b77
2 changed files with 10 additions and 12 deletions

View File

@ -18,23 +18,20 @@ function InMemoryCache(initialValue, reportError) {
return typeof value !== 'undefined' ? value : null;
},
async update(fn) {
let maybePromisedValue;
update(fn) {
try {
maybePromisedValue = fn();
const value = fn();
if (isPromiseLike(value)) {
return value.then(value => cache.set(cacheKey, value));
} else {
cache.set(cacheKey, value);
}
} catch (e) {
const errMsg = `InMemoryCache > update > caught: ${e.message}`;
e.message = errMsg;
reportError(e);
return null;
}
if (isPromiseLike(maybePromisedValue)) {
return maybePromisedValue.then(value => cache.set(cacheKey, value));
} else {
const value = maybePromisedValue;
cache.set(cacheKey, value);
return null;
}
},
clear() {

View File

@ -35,7 +35,8 @@ describe('InMemoryCache', () => {
it('can handle promises correctly', done => {
const cache = inMemoryCache(before, reportErrorStub);
cache.update(() => new Promise(resolve => resolve(after)));
const promisedUpdate = () => new Promise(resolve => resolve(after));
cache.update(promisedUpdate);
// because async
setImmediate(() => {
expect(cache.get()).toBe(after);