chore: Tidy up promise handling and testing
This commit is contained in:
committed by
mrugesh mohapatra
parent
f66e59e20c
commit
a1f64f4b77
@ -18,23 +18,20 @@ function InMemoryCache(initialValue, reportError) {
|
|||||||
return typeof value !== 'undefined' ? value : null;
|
return typeof value !== 'undefined' ? value : null;
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(fn) {
|
update(fn) {
|
||||||
let maybePromisedValue;
|
|
||||||
try {
|
try {
|
||||||
maybePromisedValue = fn();
|
const value = fn();
|
||||||
|
if (isPromiseLike(value)) {
|
||||||
|
return value.then(value => cache.set(cacheKey, value));
|
||||||
|
} else {
|
||||||
|
cache.set(cacheKey, value);
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const errMsg = `InMemoryCache > update > caught: ${e.message}`;
|
const errMsg = `InMemoryCache > update > caught: ${e.message}`;
|
||||||
e.message = errMsg;
|
e.message = errMsg;
|
||||||
reportError(e);
|
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;
|
return null;
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
|
||||||
clear() {
|
clear() {
|
||||||
|
@ -35,7 +35,8 @@ describe('InMemoryCache', () => {
|
|||||||
|
|
||||||
it('can handle promises correctly', done => {
|
it('can handle promises correctly', done => {
|
||||||
const cache = inMemoryCache(before, reportErrorStub);
|
const cache = inMemoryCache(before, reportErrorStub);
|
||||||
cache.update(() => new Promise(resolve => resolve(after)));
|
const promisedUpdate = () => new Promise(resolve => resolve(after));
|
||||||
|
cache.update(promisedUpdate);
|
||||||
// because async
|
// because async
|
||||||
setImmediate(() => {
|
setImmediate(() => {
|
||||||
expect(cache.get()).toBe(after);
|
expect(cache.get()).toBe(after);
|
||||||
|
Reference in New Issue
Block a user