Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code:

@:expose
class Main implements IAsync {    
    static function main() {
        trace("test");
    }       

    static function testAwait() {
        return 1;
    }
}

The converted code looks like this:

. . .
Main.testAwait = function() {
    return Main.test();
};
. . .

I want to replace function with async function in the code, but I am limited to changing just the method name using code macros:

package haxe_test;

import haxe.macro.Expr;
import haxe.macro.Context;   
using haxe.macro.Tools;
using haxe_test.AsyncBuilder;

class BuildHub {
    macro static public function build():Array<Field> {
        var fields = Context.getBuildFields();
        var testFunc:Function = {
            expr: macro return $v{1},
            ret: null,
            params: [],
            args: []
        };

    fields.push({
        name:  "testAwait",
        access:  [Access.AStatic],
        kind: FieldType.FFun(testFunc),
        pos: Context.currentPos(),
    });
    return fields;  
}

Is there a way to replace function with async function? UPD: The code has been simplified. Are there any compiler options or JSGenApi that can help me achieve this?

Answer №1

Have you ever thought about trying a simpler approach in Haxe 4? Here's an example of how you can achieve that:

class Test {
  static function main() {
    var value = await( async(testAsync) );
    trace(value);
  }

  static function testAsync() return 1;

  static inline function await<T>(fn:Void->Void):T {
    return js.Syntax.code("await {0}()", fn);
  }
  static inline function async<T>(fn:Void->Void):T {
      return js.Syntax.code("async () => {0}()", fn);
  }
}

You also have the option to merge the two functionalities into one like this:

class Test {
  static function main() {
    var value = asyncAwait( testAsync );
    trace(value);
  }

  static function testAsync() return 1;

  static inline function asyncAwait<T>(fn:Void->Void):T {
      return js.Syntax.code("(async () => { await {0}() })()", fn);
  }
}

Answer №2

In my opinion, there are a few possible approaches you could take:

  • Gather information about async types/fields in build macros, then utilize that data in
    haxe.macro.Context.onAfterGenerate
    to modify the output file. Since Haxe code follows consistent indentation, you may be able to achieve this using regular expressions (I once created a macro that split the output file into multiple files by package using this method).
  • Create a modified version of haxe.macro.ExampleJSGenerator to add async before specific method declarations. This approach is relatively straightforward since no changes to expression printing are necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to automatically refresh a webpage with the same URL when accessed on the same server?

Is there a way to trigger a URL page refresh using JS code located on the same server? For example, I have a URL page open on multiple devices connected to the same server. How can I ensure that when I click 'Update,' the page refreshes simultan ...

What is the process for determining the default character length in a <p> tag based on its height and width?

I'm trying to determine the default length for the <p> tag in HTML. It should be displayed based on the height and width of the <p> tag. For example: Consider the following code snippet, <p style="height:300px;width:200px;"> </ ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Encountering a problem in a NextJS application where an error occurs stating "cannot read property of undefined (reading setState)" within

In an attempt to resolve the issue, I have linked the method to this inside the constructor. Additionally, I have utilized the arrow function technique to address the problem at hand. Despite these efforts, I continue to encounter the following error: Unha ...

Utilize Electron to extract and render content from a local file into HTML code

I am struggling to find a solution for automatically reading and parsing a local csv file in an electron application. When I use 'fs' to open the file, I can't figure out how to pass the contents into the HTML window. One option is to use a ...

Display new information within a div element seamlessly without refreshing the page

Just a heads-up, I'm new to HTML development... Currently working on a website using Bootstrap. There are some buttons on the left side shown in the screenshot, and my goal is to update the content on the right without having to reload the entire pag ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...

"Utilizing AJAX to set an array as a global variable

Struggling with storing data values from an AJAX response XML into a global array, and then attempting to call a function that removes specific elements from it. The issue lies in the fact that the array is not declared as global. Here's the current c ...

What is the optimal frequency for saving data when dealing with a particularly extensive form?

I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

Discovering the true width of an element using JavaScript

Hey there, I'm currently attempting to determine the exact width of a specific element and display an alert that shows this width. The code I am using is as follows: HTML Element <table cellspacing="1" cellpadding="5" style=";width:975px;border: ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

React application experiencing issues with MQTT and Mosquitto broker connectivity

Upon installing the Mosquitto broker, I successfully tested it in my command prompt. However, when I attempted to establish a connection with my React application, I encountered the error message: "WebSocket connection to 'ws://localhost:1883/' f ...

Obtaining the designated item within the list

My list contains elements obtained from a database. I want to ensure that the selected elements remain visible at all times, even after refreshing the page. Here's an example: <select id="select-firm" class="form-control" name="firmId" size="20" ...

Troubleshooting your Meteor App on Nitrous.io with server-side debugging

I currently have a basic Meteor application up and running on a Nitrous box. I am interested in utilizing node-inspector for debugging the server-side part of my app, but I'm facing difficulty accessing the console as detailed here. The Meteor app is ...

The battle between CSS and jQuery: A guide to creating a dynamic zebra-style table without relying on additional plugins

Is there a better way to create a dynamic zebra styling for table rows while still being able to hide certain elements without losing the styling? In this code snippet, I'm using the CSS :nth-of-type(even) to style even rows but running into issues wh ...

Accessing props in react-native-testing-library and styled-components is not possible

I defined a styled-component as shown below: export const StyledButton = styled.TouchableOpacity<IButtonProps> height: 46px; width: 100%; display: flex; flex-direction: row; justify-content: center; align-items: center; height: 46px; ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

The new experimental appDir feature in Next.js 13 is failing to display <meta> or <title> tags in the <head> section when rendering on the server

I'm currently experimenting with the new experimental appDir feature in Next.js 13, and I've encountered a small issue. This project is utilizing: Next.js 13 React 18 MUI 5 (styled components using @mui/system @emotion/react @emotion/styled) T ...

Looking to eliminate curly braces from a string?

Despite my efforts to search through the site, I am still unable to resolve the issue at hand. var blah2 = JSON.stringify({foo: 123, bar: <x><y></y></x>, baz: 123}); This is what I attempted: blah2.replace(/[{}]/g, ""); Here&apo ...

Unable to display the Breadcrumb with the recursive function in PHP

Seeking assistance on implementing a recursive function method in PHP to display breadcrumbs. Here's the code I currently have: function getCategoryTreeIDs($qs_type_id) { $crumbsql = "SELECT parent_id FROM lists WHERE id=$qs_type_id"; ...