Skip to content

Commit

Permalink
Unwrap promise wrapping in IIFEs
Browse files Browse the repository at this point in the history
  • Loading branch information
rpetrich committed Jun 11, 2019
1 parent 1922a05 commit 19f1275
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 0 deletions.
28 changes: 28 additions & 0 deletions async-to-promises.ts
Expand Up @@ -3340,6 +3340,31 @@ export default function({ types, template, traverse, transformFromAst, version }
}
}

const unwrapReturnPromiseVisitor: Visitor = {
ReturnStatement(path) {
const argument = path.get("argument");
if (argument.isCallExpression()) {
switch (promiseCallExpressionType(argument.node)) {
case "all":
case "race":
case "resolve":
switch (argument.node.arguments.length) {
case 0:
path.replaceWith(types.returnStatement());
break;
case 1:
const arg0 = argument.node.arguments[0];
if (types.isExpression(arg0)) {
path.replaceWith(types.returnStatement(arg0));
}
break;
}
break;
}
}
}
};

// Main babel plugin implementation and top level visitor
return {
manipulateOptions(options: any, parserOptions: { plugins: string[] }) {
Expand Down Expand Up @@ -3422,6 +3447,9 @@ export default function({ types, template, traverse, transformFromAst, version }
if (inlineHelpers && !pathsReturnOrThrowCurrentNodes(bodyPath).all && !skipReturn) {
path.node.body.body.push(types.returnStatement(types.callExpression(promiseResolve(), [])));
}
if (skipReturn) {
path.traverse(unwrapReturnPromiseVisitor);
}
if (canThrow) {
if (inlineHelpers) {
if (skipReturn && parentPath.isCallExpression() && parentPath.node.arguments.length === 0 && !pathsReturn(bodyPath).any) {
Expand Down
1 change: 1 addition & 0 deletions tests/iife simplification with returns/hoisted.js
@@ -0,0 +1 @@
_async(function(){console.log('foo');if(foo){return console.log(foo);}})();
1 change: 1 addition & 0 deletions tests/iife simplification with returns/inlined.js
@@ -0,0 +1 @@
(function(){try{console.log('foo');if(foo){return console.log(foo);}}catch(e){Promise.reject(e);}})();
6 changes: 6 additions & 0 deletions tests/iife simplification with returns/input.js
@@ -0,0 +1,6 @@
(async function() {
console.log('foo');
if (foo) {
return console.log(foo);
}
})();
3 changes: 3 additions & 0 deletions tests/iife simplification with returns/options.json
@@ -0,0 +1,3 @@
{
"module": true
}
1 change: 1 addition & 0 deletions tests/iife simplification with returns/output.js
@@ -0,0 +1 @@
_async(()=>{console.log('foo');if(foo){return console.log(foo);}})();

0 comments on commit 19f1275

Please sign in to comment.