Handle constraints when using async handlers
masterWhen using async handlers, the implementation uses WebAssembly Asyncify to unwind the stack. This imposes strict concurrency constraints:
- No concurrent writes/ends: You must
awaitevery call to.write()and.end()before calling them again. You cannot usePromise.all()on multiple.write()calls. - Register handlers early: You cannot add new handlers via
.on()after.write()or.end()has been called. - Single use of
.end(): The.end()method can only be called once per instance. Create a newHTMLRewriterinstance for every new transformation task.
// ✅ Correct pattern for async handlers
const rewriter = new HTMLRewriter(...).on("p", {
async element(element) {
await fetch(...);
element.setInnerContent("new");
}
});
await rewriter.write(encoder.encode("<p>1</p>"));
await rewriter.write(encoder.encode("<p>2</p>"));
await rewriter.end();