Race condition with two async calls?

I have the following template with some javascript code. Its purpose is to rename a new note with a unique ID and add some frontmatter to a “plain” note. It is designed that even when called on a note with content, it should just wrap the content into a header and footer:

<%* if (tp.file.title == "Untitled")  {
	// Wenn die Datei gerade neu erzeugt wurde, hat sie noch keinen definierten Titel, er muss nachgefragt werden
	var noteTitle = await tp.system.prompt("Titel:")
} else {
	// Wenn die Datei aus einem Link erzeugt wurde, hat sie den Linknamen als Dateinamen
	var noteTitle = tp.file.title
}
fileName = noteTitle+ " ("+tp.date.now("YYYYMMDDHHmm")+")"
await tp.file.rename(fileName)

var file = app.workspace.getActiveFile()
var content = await app.vault.read(file)
var header = `---
Created: ${tp.file.creation_date()}
aliases:
  - ${noteTitle}
tags:
---
`
var footer = `

---

Modified: <%+ tp.file.last_modified_date("YYYY-MM-DD HH:mm") %>
`
var newContent = (header + content + footer).replace(/^(\r\n|\n\r)/, "")
await app.vault.modify(file, newContent)
%>

As you can see, i am using it with the Templater plugin. This is working very well when applied manually on a file, no matter if there is content or not.

My problem is: When it is applied via the Templater’s Folder template feature automatically on a new note in a folder, it results in an empty file. But i can see the desired content flash very briefly, until it is removed again, so the note is blank.

I am currently trying to understand why that happens, and why it only happens with the Folder template, not when applied manually. The whole concept of asynchronous programming in Javascript is quite new for me. The API docs are very clear that the three function calls i made with await must be called with await since they are asynchronous.

I think i have a race condition somewhere, so that one async call writes the content to the file, but afterwards another async call overwrites the file with an empty content it read before.

Could that be the right assumption? If yes, can i somehow control the order in which these asynchronous calls are made? I understand that they need to be asynchronous and awaited for, since that’s what the Obsidian API needs them to be. But i am still baffled why this race condition only occurs when the template is called as a Folder template, and not when it is called manually.

Any ideas?