You are currently offline, serving cached version

Asynchronous Data Resolving

As a reminder, Node.JS supports asynchronous code executing using two paradigms : Promises or async/await.

Using asynchronous data resolving allows you to fetch data used for your docxtemplater template asynchronously.

This means you can have promises instead of the standard JSON data to resolve information from various sources asynchronously such as HTTP requests, databases, and more.

Async rendering for the image module

If you use the image module, this option will be required because the images are usually loaded via an HTTP call (for example load the image https://docxtemplater.com/puffin.png).

Template Processing Step

The middle step (Data Resolution) can be either synchronous or asynchronous, while the other steps are always synchronous:

  • Template Compilation: The system parses your template to verify the position and validity of all tags
  • Data Resolution: The system retrieves and prepares your data (can be sync or async)
  • Template Rendering: The system combines your resolved data with the template to generate the final document

Code for async data resolution

Here is how you can render your template asynchronously.

const path = require("path");
// Compile your document
const doc = new Docxtemplater(zip, {
    paragraphLoop: true,
    linebreaks: true,
});
doc.renderAsync({
    user: new Promise((resolve) => {
        // You could also resolve your data from an HTTP request,
        // an async call to your database,
        // a call to an external API, ...
        setTimeout(() => resolve("John"), 1000);
    }),
}).then(function () {
    const buf = doc.getZip().generate({ type: "nodebuffer" });
    fs.writeFileSync(
        path.resolve(__dirname, "output.docx"),
        buf
    );
});

Using async/await syntax:

await doc.renderAsync(/* data */);
doc.getZip().generate({ type: "nodebuffer" });

To prevent blocking the main thread during document generation, use:

Talk with sales Contact us