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.
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
).
The middle step (Data Resolution) can be either synchronous or asynchronous, while the other steps are always synchronous:
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: