简体   繁体   中英

How an ANTLR visitor or listener can be written with async/await on its methods?

I am creating a grammar to compile the parser as a JavaScript parser.

Then I would like to use async/await to call asynchronous functions within the visitor or listener.

As the default generated code does not include async in the functions, await is not allowed.

How could this be achieved ?

You can't really define listeners using async because listener methods can't return anything (or rather their return values aren't used), so nothing would be done with the returned promises.

However, using async in visitors works perfectly fine. Just define your visitFoo methods as async and use await as you please. For example:

class Interpreter extends MyLangVisitor {
    async visitSleep(sleepCtx) {
        let p = new Promise(function (resolve) {
            setTimeout(resolve, sleepCtx.amount.text)
        });
        await p;
    }

    async visitProgram(programCtx) {
        for(let command of programCtx.commands) {
            await this.visit(command);
        }
    }
}

This will work fine because this.visit(command) simply returns the result of this.visitSleep(command) (or whichever other method applies), which will be a promise. So you're awaiting the promise returned by visitSleep and everything works out fine.

Do note that you shouldn't use the default visitChildren method when your methods are async because that will visit all the children without await ing them. You can easily define your own version though:

async visitChildren(ctx) {
    for(let child of ctx.children) {
        await this.visit(child);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM