Async inside visit, or unist-util-visit-async package #64
-
I'm trying to write a function remarkRunCode() {
return async (tree, file) => {
visit(tree, "code", async (node, index, parent) => {
// check for "```js run", the stuff after the space is meta
if (node.meta === "run") {
const module = await importInline(node.value);
const tree = unified().use(remarkParse).parse(module.markdown);
parent.children.splice(index, 1, ...tree.children);
console.log(parent.children.at(-1).children);
// Skip traversing children of 'node' at 'index'
return [SKIP, index];
}
});
};
}
let cacheBusts = 0;
async function importInline(code) {
let module;
try {
await fs.writeFile(".tmp.js", code);
module = await import(`./.tmp.js?q=${++cacheBusts}`);
} finally {
await fs.remove(".tmp.js");
}
return module;
} I fixed it by writing my own visit function (different semantics to the normal async function asyncVisit(node, test, callback, index, parent) {
if (is(node, test)) {
await callback(node, index, parent);
// skip children by default, since code blocks don't have children
// and that's what I'm using this for
} else if (node.children) {
for (const i in node.children) {
await asyncVisit(node.children[i], test, callback, i, node);
}
}
} But I feel this should be supported by default, either in |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Crosslinking a previous version of this question: https://spectrum.chat/unified/syntax-tree/is-there-any-way-to-execute-async-work-when-visiting-a-node-in-unist-util-visit~28177826-628e-44e3-ac3e-0ffb53c195c6 |
Beta Was this translation helpful? Give feedback.
Crosslinking a previous version of this question: https://spectrum.chat/unified/syntax-tree/is-there-any-way-to-execute-async-work-when-visiting-a-node-in-unist-util-visit~28177826-628e-44e3-ac3e-0ffb53c195c6