onDidSaveTextDocument causes infinite loop

I’m trying to create an extension that runs two formatters in succession to format a file on save.

The idea comes from this answer, so I assume it must be possible.

My extension’s code looks like this:

import * as vscode from "vscode";

export function activate(context: vscode.ExtensionContext) {

    vscode.workspace.onDidSaveTextDocument(() => {
        vscode.window.showInformationMessage('Hello World from mojo.formatter!');
        const config = vscode.workspace.getConfiguration(
          "editor",
          vscode.window.activeTextEditor?.document
        );
        const formatters = ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"];
        formatters.forEach(async (formatter) => {
          await config.update("defaultFormatter", formatter);
          await vscode.commands.executeCommand("editor.action.formatDocument");
        });
    });

}

I’ve also added the following to my package.json:

  "activationEvents": [
    "*"
  ],

Everything else is the same as it comes in the Hello world extension example.

When I save a document, the formatters run but the extension seems to create an infinite loop of

  • Saving
  • Formatting
  • Saving again
  • Formatting

And so on…

Any idea what the issue could be?