diff --git a/javascript-stringify.js b/javascript-stringify.js index f888eee..cfccee4 100644 --- a/javascript-stringify.js +++ b/javascript-stringify.js @@ -91,6 +91,16 @@ return fn.constructor.name === 'GeneratorFunction'; } + /** + * Check if a function is an ES7 async function + * + * @param {Function} fn + * @return {boolean} + */ + function isAsyncFunction (fn) { + return fn.constructor.name === 'AsyncFunction'; + } + /** * Can be replaced with `str.startsWith(prefix)` if code is updated to ES6. * @@ -281,7 +291,7 @@ if (indent) { value = dedentFunction(value); } - var prefix = isGeneratorFunction(fn) ? '*' : ''; + var prefix = isGeneratorFunction(fn) ? '*' : isAsyncFunction(fn) ? 'async ' : ''; if (fn.name && stringStartsWith(value, prefix + fn.name + '(')) { // Method notation was used to define this function, but it was transplanted from another object. // Convert to regular function notation. @@ -320,6 +330,7 @@ '[object RegExp]': String, '[object Function]': stringifyFunction, '[object GeneratorFunction]': stringifyFunction, + '[object AsyncFunction]': stringifyFunction, '[object global]': toGlobalVariable, '[object Window]': toGlobalVariable }; diff --git a/test.js b/test.js index 626e0e6..41ba89b 100644 --- a/test.js +++ b/test.js @@ -207,6 +207,10 @@ describe('javascript-stringify', function () { it('should stringify', testRoundTrip('function* (x) { yield x; }')); }); + describe('async', function () { + it('should stringify', testRoundTrip('async function (x) { await x; }')); + }); + describe('method notation', function () { it('should stringify', testRoundTrip('{a(b, c) { return b + c; }}')); @@ -222,6 +226,11 @@ describe('javascript-stringify', function () { testRoundTrip("{*'function a'(b, c) { return b + c; }}") ); + it( + 'should not be fooled by tricky async names', + testRoundTrip("{async 'function a'(b, c) { return b + c; }}") + ); + it( 'should not be fooled by empty names', testRoundTrip("{''(b, c) { return b + c; }}")