Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix async arrow functions
  • Loading branch information
jquense committed Sep 20, 2016
1 parent bc263de commit 2ee9e97
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/babel/index.js
Expand Up @@ -14,15 +14,20 @@ const buildTagger = template(`
})();
`);

const buildNewClassProperty = (t, classPropertyName, newMethodName) => {
const returnExpression = t.callExpression(
const buildNewClassProperty = (t, classPropertyName, newMethodName, isAsync) => {
let returnExpression = t.callExpression(
t.memberExpression(t.thisExpression(), newMethodName),
[t.spreadElement(t.identifier('params'))]
);

if (isAsync) {
returnExpression = t.awaitExpression(returnExpression);
}

const newArrowFunction = t.arrowFunctionExpression(
[t.restElement(t.identifier('params'))],
returnExpression
returnExpression,
isAsync
);
return t.classProperty(classPropertyName, newArrowFunction);
};
Expand Down Expand Up @@ -176,6 +181,7 @@ module.exports = function plugin(args) {

// class property node value is nullable
if (node.value && node.value.type === 'ArrowFunctionExpression') {
const isAsync = node.value.async;
const params = node.value.params;
const newIdentifier = t.identifier(`__${node.key.name}__REACT_HOT_LOADER__`);

Expand All @@ -187,11 +193,12 @@ module.exports = function plugin(args) {
// create a new method on the class that the original class property function
// calls, since the method is able to be replaced by RHL
const newMethod = t.classMethod('method', newIdentifier, params, newMethodBody);
newMethod.async = isAsync;
path.insertAfter(newMethod);

// replace the original class property function with a function that calls
// the new class method created above
path.replaceWith(buildNewClassProperty(t, node.key, newIdentifier));
path.replaceWith(buildNewClassProperty(t, node.key, newIdentifier, isAsync));
}
}
});
Expand Down
6 changes: 6 additions & 0 deletions test/babel/fixtures/async-functions/.babelrc
@@ -0,0 +1,6 @@
{
"plugins": [
"syntax-class-properties",
"../../../../src/babel"
]
}
5 changes: 5 additions & 0 deletions test/babel/fixtures/async-functions/actual.js
@@ -0,0 +1,5 @@
class Foo {
bar = async (a, b) => {
return await a(b);
};
}
21 changes: 21 additions & 0 deletions test/babel/fixtures/async-functions/expected.js
@@ -0,0 +1,21 @@
var _this = this;

class Foo {
bar = async (...params) => await _this.__bar__REACT_HOT_LOADER__(...params);

async __bar__REACT_HOT_LOADER__(a, b) {
return await a(b);
}

}
;

(function () {
if (typeof __REACT_HOT_LOADER__ === 'undefined') {
return;
}

__REACT_HOT_LOADER__.register(Foo, "Foo", __FILENAME__);
})();

;

0 comments on commit 2ee9e97

Please sign in to comment.