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

Commit

Permalink
handle async functions (#19)
Browse files Browse the repository at this point in the history
* add  async Wrapper

* avoid eval

* only handle async function

* add typing test to see if we can pass async functions
  • Loading branch information
Uzlopak authored May 15, 2022
1 parent d264881 commit 6bd455b
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 3 deletions.
61 changes: 58 additions & 3 deletions benchmark.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,31 @@

/*--------------------------------------------------------------------------*/

var isAsyncFunction;
try {
var asyncFunctionPrototype = new Function('return Object.getPrototypeOf(async function () { })')();
isAsyncFunction = function (fn) {
try {
return (
(
typeof fn === 'string' &&
asyncFunctionPrototype === Object.getPrototypeOf(new Function(fn))
) ||
(
typeof fn === 'function' &&
Object.getPrototypeOf(fn) === asyncFunctionPrototype
)
);
} catch (e) {
return false;
}
};
} catch (e) {
isAsyncFunction = function () {
return false;
}
}

/**
* A specialized version of lodashs `cloneDeep` which only clones arrays and plain
* objects assigning all other values by reference.
Expand Down Expand Up @@ -980,9 +1005,39 @@
}

function add(name, fn, options) {
var suite = this,
bench = new Benchmark(name, fn, options),
event = Event({ 'type': 'add', 'target': bench });
var suite = this;
var bench;
if (isAsyncFunction(fn)) {
if (typeof fn === 'function') {
bench = new Benchmark(name,
{
defer: true,
fn: function (deferred) {
fn()
.catch(function (error) {
deferred.reject(error);
})
.then(function () {
deferred.resolve();
});
}
},
options);
} else {
bench = new Benchmark(name,
{
defer: true,
fn: '(' + fn + ')()' +
'.catch(function (error) { deferred.reject(error); })' +
'.then(function () { deferred.resolve(); })'
},
options)
}
} else {
bench = new Benchmark(name, fn, options);
}

var event = Event({ 'type': 'add', 'target': bench });

if (suite.emit(event), !event.cancelled) {
suite.push(bench);
Expand Down
2 changes: 2 additions & 0 deletions test/types/types-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ suite.add(fn);
// or using a name first
suite.add('foo', fn);

suite.add('async', async function() {});

// or with options
suite.add('foo', fn, {
'onCycle': onCycle,
Expand Down

0 comments on commit 6bd455b

Please sign in to comment.