Skip to content
This repository has been archived by the owner on May 5, 2023. It is now read-only.

Commit

Permalink
Fix regular sync functions into async
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Oct 18, 2019
1 parent 7a144af commit 66f0229
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
9 changes: 8 additions & 1 deletion src/generator-to-promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,17 @@ export default function generatorToPromise<T>(
generatorFunction: any
): (...args: any[]) => Promise<T> {
if (!isGen(generatorFunction)) {
if (typeof generatorFunction === 'function') {
return function(this: any) {
return Promise.resolve(true).then(() =>
generatorFunction.call(this, arguments)
);
};
}
throw new Error('The given function must be a generator function');
}

return function invoker(this: any) {
return function(this: any) {
const deferred = createDeferred<T>();
const generator = generatorFunction.call(this, arguments);
(function next(error?: Error | null, value?: any) {
Expand Down
11 changes: 10 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,23 @@ namespace degenerator {
options.sandbox,
options
);
if (supportsAsync) {
if (typeof fn !== 'function') {
throw new Error(
`Expected a function to be returned, but got ${typeof fn}`
);
}
if (isAsyncFunction(fn)) {
return fn as T;
} else {
return (generatorToPromise(fn) as unknown) as T;
}
}
}

function isAsyncFunction(fn: any): boolean {
return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction';
}

/**
* Returns `true` if `node` has a matching name to one of the entries in the
* `names` array.
Expand Down
32 changes: 32 additions & 0 deletions test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,37 @@ describe('degenerator()', () => {
done();
}, done);
});
it('should be able to compile functions with no async', done => {
const a = () => 'a';
const b = () => 'b';
function aPlusB(): string {
return a() + b();
}
const fn = compile<() => Promise<string>>(
'' + aPlusB,
'aPlusB',
[],
{
sandbox: { a, b }
}
);
fn().then((val: string) => {
assert.equal(val, 'ab');
done();
}, done);
});
it('should throw an Error if no function is returned from the `vm`', () => {
let err;
try {
compile<() => Promise<string>>('const foo = 1', 'foo', []);
} catch (_err) {
err = _err;
}
assert(err);
assert.equal(
err.message,
'Expected a function to be returned, but got number'
);
});
});
});

0 comments on commit 66f0229

Please sign in to comment.