Skip to content

Commit

Permalink
feat(vowTools): asVow does not wrap vows as a vow
Browse files Browse the repository at this point in the history
  • Loading branch information
0xpatrickdev committed Jun 25, 2024
1 parent 316fe97 commit cf3f9c4
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
11 changes: 8 additions & 3 deletions packages/vow/src/vow-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,17 @@ export const makeAsVow = makeVowKit => {
* @returns {Vow<Awaited<T>>}
*/
const asVow = fn => {
const kit = makeVowKit();
let result;
try {
kit.resolver.resolve(fn());
result = fn();
} catch (e) {
kit.resolver.reject(e);
result = Promise.reject(e);
}
if (isVow(result)) {
return result;
}
const kit = makeVowKit();
kit.resolver.resolve(result);
return kit.vow;
};
return harden(asVow);
Expand Down
21 changes: 17 additions & 4 deletions packages/vow/test/asVow.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@ import { prepareVowTools } from '../src/tools.js';
import { isVow } from '../src/vow-utils.js';

test('asVow takes a function that throws/returns synchronously and returns a vow', async t => {
const zone = makeHeapZone();
const { watch, when, asVow } = prepareVowTools(zone);
const { watch, when, asVow } = prepareVowTools(makeHeapZone());

const fnThatThrows = () => {
throw Error('fail');
};

const vowWithRejection = asVow(fnThatThrows);
t.true(isVow(vowWithRejection));
await t.throwsAsync(when(vowWithRejection), { message: 'fail' }, 'failure ');
await t.throwsAsync(
when(vowWithRejection),
{ message: 'fail' },
'error should propogate as promise rejection',
);

const isWatchAble = watch(asVow(fnThatThrows));
t.true(isVow(vowWithRejection));
await t.throwsAsync(when(isWatchAble), { message: 'fail' }, 'failure ');
await t.throwsAsync(when(isWatchAble), { message: 'fail' });

const fnThatReturns = () => {
return 'early return';
Expand All @@ -30,3 +33,13 @@ test('asVow takes a function that throws/returns synchronously and returns a vow
t.is(await when(vowWithReturn), 'early return');
t.is(await when(watch(vowWithReturn)), 'early return');
});

test('asVow does not resolve a vow to a vow', async t => {
const { watch, asVow } = prepareVowTools(makeHeapZone());

const testVow = watch(Promise.resolve('payload'));
const testVowAsVow = asVow(() => testVow);

t.is(testVow, testVowAsVow, 'asVow does not rewrap vows');
t.is(await testVow, await testVowAsVow, 'result is preserved');
});

0 comments on commit cf3f9c4

Please sign in to comment.